public LockManager(@NonNull final Configuration conf) { this.lockConf = new LockManagerConfiguration(conf); this.isEnabled = lockConf.isEnabled(); this.lockMap = new ConcurrentHashMap(); if (this.isEnabled) { final ZookeeperConfiguration zkConf = new ZookeeperConfiguration(conf); this.client = Optional.of(CuratorFrameworkFactory.builder() .connectString(zkConf.getZkQuorum()) .retryPolicy(new BoundedExponentialBackoffRetry(1000, 5000, 3)) .namespace(lockConf.getZkBasePath()) .sessionTimeoutMs(lockConf.getZkSessionTimeoutMs()) .connectionTimeoutMs(lockConf.getZkConnectionTimeoutMs()) .build()); this.client.get().start(); } else { this.client = Optional.absent(); } }
public LockManagerConfiguration(@NonNull final Configuration conf) { this.conf = conf; this.isEnabled = this.getConf().getBooleanProperty(IS_ENABLED, DEFAULT_IS_ENABLED); if (this.isEnabled()) { ConfigUtil.checkMandatoryProperties(conf, getMandatoryProperties()); this.zkBasePath = cleanZkBasePath(this.getConf().getProperty(ZK_BASE_PATH).get()); } else { this.zkBasePath = null; } this.zkSessionTimeoutMs = this.getConf().getIntProperty(ZK_SESSION_TIMEOUT_MS, DEFAULT_ZK_SESSION_TIMEOUT_MS); this.zkConnectionTimeoutMs = this.getConf().getIntProperty(ZK_CONNECTION_TIMEOUT_MS, DEFAULT_ZK_CONNECTION_TIMEOUT_MS); this.acquireLockTimeMs = this.getConf().getIntProperty(ACQUIRE_LOCK_TIME_MS, DEFAULT_ACQUIRE_LOCK_TIME_MS); }
private boolean acquireLock(@NonNull final InterProcessMutex lock) throws Exception { return lock.acquire(lockConf.getAcquireLockTimeMs(), TimeUnit.MILLISECONDS); }
@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); } }