private void testTryLockFunction(final IClusterLockService service) throws InterruptedException {
reset(portalInfoProvider);
when(portalInfoProvider.getUniqueServerName()).thenReturn("ServerA");
final ThreadGroupRunner threadGroupRunner = new ThreadGroupRunner("ClusterLockServiceImplTest-", true);
final String mutexName = "testLockFunction";
final AtomicInteger executionCounter = new AtomicInteger(0);
final AtomicBoolean concurrent = new AtomicBoolean(false);
final AtomicInteger trueCounter = new AtomicInteger(0);
final AtomicInteger falseCounter = new AtomicInteger(0);
final int threads = 3;
threadGroupRunner.addTask(threads, new ThrowingRunnable() {
@Override
public void runWithException() throws Throwable {
execute(new Callable<Object>() {
@Override
public Object call() throws Exception {
threadGroupRunner.tick(1);
final TryLockFunctionResult<Object> result = service.doInTryLock(mutexName, new Function<ClusterMutex, Object>() {
@Override
public Object apply(ClusterMutex input) {
if (concurrent.getAndSet(true)) {
fail("Only one thread should be in Function at a time");
}
try {
executionCounter.incrementAndGet();
logger.debug("Starting 1500ms of work");
Thread.sleep(1500);
logger.debug("Completed 1500ms of work");
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
concurrent.set(false);
}
return null;
}
});
if (result.isExecuted()) {
trueCounter.incrementAndGet();
}
else {
falseCounter.incrementAndGet();
}
return result;
}
});
}
});
threadGroupRunner.start();
threadGroupRunner.join();
assertEquals(1, executionCounter.get());
assertEquals(1, trueCounter.get());
assertEquals(threads - 1, falseCounter.get());
assertFalse(concurrent.get());