List of usage examples for java.util.concurrent.locks Lock newCondition
Condition newCondition();
From source file:org.jactr.core.production.action.SleepAction.java
/** * wait until the goal buffer isn't empty * /*from www . j av a 2 s. co m*/ * @see org.jactr.core.production.action.IAction#fire(org.jactr.core.production.IInstantiation, double) */ public double fire(IInstantiation instantiation, double firingTime) { IActivationBuffer goalBuffer = instantiation.getModel().getActivationBuffer(IActivationBuffer.GOAL); if (goalBuffer.getSourceChunk() == null) { final Lock goalLock = new ReentrantLock(); final Condition gotAGoal = goalLock.newCondition(); /* * merely signal when the goal buffer gets something */ IActivationBufferListener listener = new ActivationBufferListenerAdaptor() { @Override public void sourceChunkAdded(ActivationBufferEvent event) { try { goalLock.lock(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Signaling goal insertion"); gotAGoal.signalAll(); } finally { goalLock.unlock(); } } }; /* * attach the listener with the inline executor - this ensures that * regardless of what thread adds the source chunk to the buffer we will * be notified */ goalBuffer.addListener(listener, ExecutorServices.INLINE_EXECUTOR); try { goalLock.lock(); while (goalBuffer.getSourceChunk() == null) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Waiting for goal"); gotAGoal.await(); } } catch (Exception e) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Could not wait for goal ", e); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Resuming from wait"); goalLock.unlock(); /* * remove the listener */ goalBuffer.removeListener(listener); } else if (LOGGER.isDebugEnabled()) LOGGER.debug("Goal is already present, no need to sleep"); return 0; }