Skip to content

Commit a099e41

Browse files
Locking listenable future executor added
1 parent 54833de commit a099e41

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Copyright 2009-2016 the original author or authors.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package net.javacrumbs.shedlock.spring;
17+
18+
import net.javacrumbs.shedlock.core.LockConfiguration;
19+
import net.javacrumbs.shedlock.core.LockProvider;
20+
import net.javacrumbs.shedlock.core.SimpleLock;
21+
import org.slf4j.Logger;
22+
import org.slf4j.LoggerFactory;
23+
import org.springframework.util.concurrent.ListenableFuture;
24+
25+
import java.util.Optional;
26+
import java.util.concurrent.Callable;
27+
28+
import static java.util.Objects.requireNonNull;
29+
30+
public class LockingListenableFutureExecutor {
31+
private static final Logger logger = LoggerFactory.getLogger(LockingListenableFutureExecutor.class);
32+
private final LockProvider lockProvider;
33+
34+
public LockingListenableFutureExecutor(LockProvider lockProvider) {
35+
this.lockProvider = requireNonNull(lockProvider);
36+
}
37+
38+
public void executeWithLock(Callable<ListenableFuture<?>> task, LockConfiguration lockConfig) {
39+
Optional<SimpleLock> lockOpt = lockProvider.lock(lockConfig);
40+
String lockName = lockConfig.getName();
41+
if (lockOpt.isPresent()) {
42+
SimpleLock lock = lockOpt.get();
43+
try {
44+
logger.debug("Locked {}.", lockName);
45+
task.call().addCallback(r -> unlock(lock, lockName), e -> unlock(lock, lockName));
46+
} catch (Exception e) {
47+
logger.info("Error when executing task", e);
48+
unlock(lock, lockName);
49+
}
50+
} else {
51+
logger.info("Not executing {}. It's locked.", lockName);
52+
}
53+
}
54+
55+
private void unlock(SimpleLock lock, String lockConfigName) {
56+
lock.unlock();
57+
logger.debug("Unlocked {}.", lockConfigName);
58+
}
59+
}

0 commit comments

Comments
 (0)