use of com.twitter.distributedlog.lock.ZKSessionLock in project distributedlog by twitter.
the class TestZKSessionLock method testLockWhenSomeoneHeldLock.
/**
* Test lock if the lock is already held by someone else. Any lock in this situation will
* fail with current owner.
*
* @param timeout
* timeout to wait for the lock
* @throws Exception
*/
private void testLockWhenSomeoneHeldLock(long timeout) throws Exception {
String lockPath = "/test-lock-nowait-" + timeout + "-" + System.currentTimeMillis();
String clientId0 = "test-lock-nowait-0-" + System.currentTimeMillis();
String clientId1 = "test-lock-nowait-1-" + System.currentTimeMillis();
String clientId2 = "test-lock-nowait-2-" + System.currentTimeMillis();
createLockPath(zkc.get(), lockPath);
ZKSessionLock lock0 = new ZKSessionLock(zkc0, lockPath, clientId0, lockStateExecutor);
ZKSessionLock lock1 = new ZKSessionLock(zkc, lockPath, clientId1, lockStateExecutor);
lock0.tryLock(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// verification after lock0 lock
assertEquals(State.CLAIMED, lock0.getLockState());
List<String> children = getLockWaiters(zkc0, lockPath);
assertEquals(1, children.size());
assertEquals(lock0.getLockId(), Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
try {
lock1.tryLock(timeout, TimeUnit.MILLISECONDS);
fail("lock1 should fail on locking since lock0 is holding the lock.");
} catch (OwnershipAcquireFailedException oafe) {
assertEquals(lock0.getLockId().getLeft(), oafe.getCurrentOwner());
}
// verification after lock1 tryLock
assertEquals(State.CLAIMED, lock0.getLockState());
assertEquals(State.CLOSED, lock1.getLockState());
children = getLockWaiters(zkc0, lockPath);
assertEquals(1, children.size());
assertEquals(lock0.getLockId(), Await.result(asyncParseClientID(zkc0.get(), lockPath, children.get(0))));
lock0.unlock();
// verification after unlock lock0
assertEquals(State.CLOSED, lock0.getLockState());
assertEquals(0, getLockWaiters(zkc, lockPath).size());
ZKSessionLock lock2 = new ZKSessionLock(zkc, lockPath, clientId2, lockStateExecutor);
lock2.tryLock(timeout, TimeUnit.MILLISECONDS);
// verification after lock2 lock
assertEquals(State.CLOSED, lock0.getLockState());
assertEquals(State.CLOSED, lock1.getLockState());
assertEquals(State.CLAIMED, lock2.getLockState());
children = getLockWaiters(zkc, lockPath);
assertEquals(1, children.size());
assertEquals(lock2.getLockId(), Await.result(asyncParseClientID(zkc.get(), lockPath, children.get(0))));
lock2.unlock();
}
Aggregations