@Override public void close() { if (!this.isEnabled) { log.info("The LockManager is not enabled. Closing it anyways."); return; } lockMap.forEach((key, mutex) -> { try { unlock(key); lockMap.remove(key); } catch (Exception e) { throw new JobRuntimeException("Failed to close the LockManager", e); } } ); if (client.isPresent()) { client.get().close(); client = Optional.absent(); } }
public boolean batchLock(@NotEmpty final List<String> lockKeyList, final String lockInfo) throws JobRuntimeException { final List<String> locked = new ArrayList(); final AtomicBoolean isSuccess = new AtomicBoolean(true); try { for (final String lockKey : lockKeyList) { if (this.lock(lockKey, lockInfo)) { locked.add(lockKey); } else { isSuccess.set(false); break; } } } catch (Exception e) { isSuccess.set(false); new JobRuntimeException("Failed to lock all keys at once", e); } finally { if (!isSuccess.get()) { log.info("Failed to lock all keys at once, will release them."); log.info("The requested lock list is " + lockKeyList); log.info("The locked list is " + locked); for (final String lockKey : locked) { this.unlock(lockKey); } } return isSuccess.get(); } }
@Test public void testLockInfo() throws Exception { final String LOCK_INFO = "This is the information in the lock"; final String key1 = LockManager.getLockKey("test_lock", "key1"); try (final LockManager lockManager = new LockManager(conf)) { assertTrue(lockManager.lock(key1, LOCK_INFO)); final LockManagerConfiguration lockConf = new LockManagerConfiguration(conf); final ZookeeperConfiguration zkConf = new ZookeeperConfiguration(conf); final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(zkConf.getZkQuorum()) .retryPolicy(new BoundedExponentialBackoffRetry(1000, 5000, 3)) .namespace(lockConf.getZkBasePath()) .sessionTimeoutMs(lockConf.getZkSessionTimeoutMs()) .connectionTimeoutMs(lockConf.getZkConnectionTimeoutMs()) .build(); client.start(); final String node = client.getChildren().forPath(key1).get(0); final String data = new String(client.getData().forPath(key1 + "/" + node)); assertEquals(LOCK_INFO, data); client.close(); lockManager.unlock(key1); } }
@Override public Void call() throws Exception { try (final LockManager lockManager = new LockManager(conf)) { coordinator.waitUntilStep(0); assertTrue(lockManager.lock(key1, "")); coordinator.nextStep(); coordinator.waitUntilStep(2); assertTrue(lockManager.unlock(key1)); } finally { coordinator.nextStep(); return null; } } };