List of usage examples for org.apache.zookeeper.recipes.lock WriteLock setLockListener
public synchronized void setLockListener(LockListener callback)
From source file:io.teknek.daemon.TeknekDaemon.java
License:Apache License
private void considerStarting(String child) throws WorkerDaoException { Plan plan = WorkerDao.findPlanByName(reKeeper.getZooKeeper(), child); if (plan == null) { logger.warn(String.format("Did not find a valid plan under node name %s", child)); return;/*from w w w . ja va2s .c om*/ } if (!child.equals(plan.getName())) { logger.warn(String.format("Node name %s is not the same is the json value %s will not start", child, plan.getName())); return; } List<String> workerUuidsWorkingOnPlan = WorkerDao.findWorkersWorkingOnPlan(reKeeper.getZooKeeper(), plan); if (alreadyAtMaxWorkersPerNode(plan, workerUuidsWorkingOnPlan, workerThreads.get(plan))) { return; } if (!isPlanSane(plan)) { return; } logger.debug("trying to acqure lock on " + WorkerDao.LOCKS_ZK + "/" + plan.getName()); WorkerDao.maybeCreatePlanLockDir(reKeeper.getZooKeeper(), plan); final CountDownLatch c = new CountDownLatch(1); WriteLock l = new WriteLock(reKeeper.getZooKeeper(), WorkerDao.LOCKS_ZK + "/" + plan.getName(), null); l.setLockListener(new LockListener() { @Override public void lockAcquired() { logger.debug(myId + " counting down"); c.countDown(); } @Override public void lockReleased() { logger.debug(myId + " released"); } }); boolean hasLatch = false; try { boolean gotLock = l.lock(); if (!gotLock) { logger.debug("did not get lock"); return; } hasLatch = c.await(3000, TimeUnit.MILLISECONDS); if (hasLatch) { plan = WorkerDao.findPlanByName(reKeeper.getZooKeeper(), child); if (plan.isDisabled()) { logger.debug("disabled " + plan.getName()); return; } List<String> workerUuids = WorkerDao.findWorkersWorkingOnPlan(reKeeper.getZooKeeper(), plan); if (workerUuids.size() >= plan.getMaxWorkers()) { logger.debug("already running max children:" + workerUuids.size() + " planmax:" + plan.getMaxWorkers() + " running:" + workerUuids); return; } logger.debug("starting worker"); try { Worker worker = new Worker(plan, workerUuids, this); worker.init(); worker.start(); addWorkerToList(plan, worker); } catch (RuntimeException e) { throw new WorkerStartException(e); } } } catch (KeeperException | InterruptedException | WorkerDaoException | WorkerStartException e) { logger.warn("getting lock", e); } finally { try { l.unlock(); } catch (RuntimeException ex) { logger.warn("Unable to unlock/cleanup. hadlock?" + hasLatch, ex); } } }