Java Code Examples for java.util.concurrent.locks.Condition

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/ext/impl/.

Source file: DefaultExecutionControlStrategy.java

  22 
vote

/** 
 * Indicate that the execution iteration for the given actor should be resumed. <br/> If the actor was not paused, this call has no impact, but just returns false.
 * @param actor
 * @return true if actor iteration was paused before this callfalse if actor is not paused.
 */
public boolean resume(Actor actor){
  Condition pauseCondition=pausedActors.remove(actor);
  if (pauseCondition != null) {
    pauseCondition.signalAll();
    return true;
  }
 else {
    return false;
  }
}
 

Example 2

From project menagerie, under directory /src/test/java/org/menagerie/locks/.

Source file: ReentrantZkLock2Test.java

  22 
vote

@Test(timeout=1000l) @Ignore("Ignored until Conditions are fully implemented in ReentrantZkLock2") public void testConditionTimesOut() throws Exception {
  Lock firstLock=new ReentrantZkLock2(baseLockPath,zkSessionManager);
  Condition firstCondition=firstLock.newCondition();
  firstLock.lock();
  boolean timedOut=firstCondition.await(250l,TimeUnit.MILLISECONDS);
  assertTrue("Condition did not time out!",!timedOut);
  firstLock.unlock();
}
 

Example 3

From project menagerie, under directory /src/test/java/org/menagerie/locks/.

Source file: ReentrantZkLockTest.java

  22 
vote

@Test(timeout=1000l) public void testConditionTimesOut() throws Exception {
  Lock firstLock=new ReentrantZkLock(baseLockPath,zkSessionManager);
  Condition firstCondition=firstLock.newCondition();
  firstLock.lock();
  boolean timedOut=firstCondition.await(250l,TimeUnit.MILLISECONDS);
  assertTrue("Condition did not time out!",!timedOut);
  firstLock.unlock();
}
 

Example 4

From project clustermeister, under directory /provisioning/src/test/java/com/github/nethad/clustermeister/provisioning/jppf/.

Source file: PublicIpIntegrationTest.java

  21 
vote

@Test public void testDriverBlockingUntilPublicIpAvailable() throws InterruptedException {
  final Lock lock=new ReentrantLock();
  final Condition condition=lock.newCondition();
  final AtomicBoolean isBlocking=new AtomicBoolean(false);
  final JPPFLocalDriver driver=new JPPFLocalDriver(null);
  new Thread(new Runnable(){
    @Override public void run(){
      lock.lock();
      try {
        isBlocking.set(true);
        condition.signal();
      }
  finally {
        lock.unlock();
      }
      driver.getIpAddress();
    }
  }
).start();
  lock.lock();
  try {
    while (!isBlocking.get()) {
      condition.await();
      Thread.sleep(100);
    }
  }
  finally {
    lock.unlock();
  }
  nodeDeployer.addListener(driver);
  assertThat(driver.getIpAddress(),is("1.2.3.5"));
}
 

Example 5

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/ext/impl/.

Source file: DefaultExecutionControlStrategy.java

  21 
vote

/** 
 * Default implementation, returning immediately for all requests, i.e. no synchronization/stepping/... whatsoever.
 */
public IterationPermission requestNextIteration(Actor actor){
  if (logger.isTraceEnabled())   logger.trace("requestNextIteration() - entry - actor " + ((NamedObj)actor).getName());
  try {
    Condition pauseIndicator=pausedActors.get(actor);
    if (pauseIndicator != null) {
      try {
        pauseLock.lockInterruptibly();
        pauseIndicator.await(1,TimeUnit.SECONDS);
      }
 catch (      InterruptedException e) {
      }
      return null;
    }
 else     if (delegate != null) {
      return delegate.requestNextIteration(actor);
    }
 else {
      return null;
    }
  }
  finally {
    if (logger.isTraceEnabled())     logger.trace("requestNextIteration() - exit");
  }
}
 

Example 6

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/conn/tsccm/.

Source file: TestSpuriousWakeup.java

  21 
vote

@Test public void testSpuriousWakeup() throws Exception {
  SchemeRegistry schreg=new SchemeRegistry();
  SchemeSocketFactory sf=PlainSocketFactory.getSocketFactory();
  schreg.register(new Scheme("http",80,sf));
  XTSCCM mgr=new XTSCCM(schreg);
  try {
    mgr.setMaxTotal(1);
    mgr.setDefaultMaxPerRoute(1);
    ClientConnectionRequest connRequest=mgr.requestConnection(ROUTE,null);
    ManagedClientConnection conn=connRequest.getConnection(0,null);
    Assert.assertNotNull(conn);
    GetConnThread gct=new GetConnThread(mgr,ROUTE,0L);
    gct.start();
    Thread.sleep(100);
    Assert.assertEquals("thread not waiting",Thread.State.WAITING,gct.getState());
    Lock lck=mgr.extendedCPBR.getLock();
    Condition cnd=mgr.extendedCPBR.newestWT.getCondition();
    for (int i=0; i < 3; i++) {
      if (i > 0)       Thread.sleep(333);
      try {
        lck.lock();
        cnd.signalAll();
      }
  finally {
        lck.unlock();
      }
      Thread.sleep(100);
      Assert.assertEquals("thread no longer waiting, iteration " + i,Thread.State.WAITING,gct.getState());
    }
  }
  finally {
    mgr.shutdown();
  }
}
 

Example 7

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/conn/tsccm/.

Source file: TestWaitingThread.java

  21 
vote

@Test public void testConstructor(){
  try {
    new WaitingThread(null,null);
    Assert.fail("null condition not detected");
  }
 catch (  IllegalArgumentException iax) {
  }
  Lock lck=new ReentrantLock();
  Condition cnd=lck.newCondition();
  WaitingThread wt=new WaitingThread(cnd,null);
  Assert.assertEquals("wrong condition",cnd,wt.getCondition());
  Assert.assertNull("pool from nowhere",wt.getPool());
  Assert.assertNull("thread from nowhere",wt.getThread());
  HttpRoute route=new HttpRoute(TARGET);
  ConnPerRoute connPerRoute=new ConnPerRouteBean(10);
  RouteSpecificPool rospl=new RouteSpecificPool(route,connPerRoute);
  wt=new WaitingThread(cnd,rospl);
  Assert.assertEquals("wrong condition",cnd,wt.getCondition());
  Assert.assertEquals("wrong pool",rospl,wt.getPool());
  Assert.assertNull("thread from nowhere",wt.getThread());
}
 

Example 8

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/conn/tsccm/.

Source file: WaitingThread.java

  19 
vote

/** 
 * Creates a new entry for a waiting thread.
 * @param cond      the condition for which to wait
 * @param pool      the pool on which the thread will be waiting,or <code>null</code>
 */
public WaitingThread(Condition cond,RouteSpecificPool pool){
  if (cond == null) {
    throw new IllegalArgumentException("Condition must not be null.");
  }
  this.cond=cond;
  this.pool=pool;
}
 

Example 9

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/windowing/.

Source file: DefaultWindowFuture.java

  19 
vote

/** 
 * Creates a new DefaultWindowFuture.
 * @param window The window that created this future.  Saved as a weakreference to prevent circular references.
 * @param windowLock The shared lock from the window
 * @param completedCondition The shared condition to wait on
 * @param key The key of the future
 * @param request The request of the future
 * @param callerStateHint The initial state of the caller hint
 * @param originalOfferTimeoutMillis
 * @param windowSize Size of the window after this request was added. Usefulfor calculating an estimated response time for this request rather than all requests ahead of it in the window.
 * @param offerTimestamp The timestamp when the request was offered
 * @param acceptTimestamp The timestamp when the request was accepted
 * @param expireTimestamp The timestamp when the request will expire or -1if no expiration is set
 */
protected DefaultWindowFuture(Window window,ReentrantLock windowLock,Condition completedCondition,K key,R request,int callerStateHint,long originalOfferTimeoutMillis,int windowSize,long offerTimestamp,long acceptTimestamp,long expireTimestamp){
  this.window=new WeakReference<Window>(window);
  this.windowLock=windowLock;
  this.completedCondition=completedCondition;
  this.key=key;
  this.request=request;
  this.response=new AtomicReference<P>();
  this.cause=new AtomicReference<Throwable>();
  this.callerStateHint=new AtomicInteger(callerStateHint);
  this.done=new AtomicBoolean(false);
  this.originalOfferTimeoutMillis=originalOfferTimeoutMillis;
  this.windowSize=windowSize;
  this.offerTimestamp=offerTimestamp;
  this.acceptTimestamp=acceptTimestamp;
  this.expireTimestamp=expireTimestamp;
  this.doneTimestamp=new AtomicLong(0);
}
 

Example 10

From project flume, under directory /flume-ng-sinks/flume-ng-hbase-sink/src/main/java/org/apache/flume/sink/hbase/.

Source file: AsyncHBaseSink.java

  19 
vote

public FailureCallback(Lock lck,AtomicInteger callbacksReceived,AtomicBoolean txnFail,Condition condition){
  this.lock=lck;
  this.callbacksReceived=callbacksReceived;
  this.txnFail=txnFail;
  this.condition=condition;
}
 

Example 11

From project graph-collections, under directory /src/test/java/org/neo4j/collections/list/.

Source file: TestUnrolledLinkedListConcurrency.java

  19 
vote

public StateSynchronizer(Class<? extends Enum> states){
  lock=new ReentrantLock();
  conditions=new HashMap<Enum,Condition>();
  for (  Enum state : states.getEnumConstants()) {
    conditions.put(state,lock.newCondition());
  }
}
 

Example 12

From project linkedin-utils, under directory /org.linkedin.util-core/src/main/java/org/linkedin/util/concurrent/.

Source file: ConcurrentUtils.java

  19 
vote

/** 
 * Waits on the condition but if end time is expired then throws an exception. On purpose this method does not synchronize on the lock because it must be called from a block which synchronizes on it
 * @param condition the condition to wait on
 * @param endTime the time after which an exception is thrown (comparedto  {@link java.lang.System#currentTimeMillis()}. If &lt; 0 then wait indefinitely (so <code>TimeOutException</code> will not be thrown!)
 * @throws InterruptedException if the thread is interrupted while waiting
 * @throws TimeoutException if the time has been reached 
 */
public static void awaitUntil(Clock clock,Condition condition,long endTime) throws InterruptedException, TimeoutException {
  if (endTime <= 0)   condition.await();
 else {
    long now=clock.currentTimeMillis();
    if (now >= endTime)     throw new TimeoutException("timeout reached while waiting on the lock: " + condition);
    if (!condition.await(endTime - now,TimeUnit.MILLISECONDS))     throw new TimeoutException("timeout reached while waiting on the lock: " + condition);
  }
}
 

Example 13

From project Metamorphosis, under directory /metamorphosis-commons/src/main/java/com/taobao/common/store/journal/.

Source file: DataFile.java

  19 
vote

void sync(final Condition condition) throws Exception {
  while (this.fc.position() < this.currentPos) {
    condition.await(1,TimeUnit.SECONDS);
  }
  this.fc.force(true);
}
 

Example 14

From project platform_external_apache-http, under directory /src/org/apache/http/impl/conn/tsccm/.

Source file: WaitingThread.java

  19 
vote

/** 
 * Creates a new entry for a waiting thread.
 * @param cond      the condition for which to wait
 * @param pool      the pool on which the thread will be waiting,or <code>null</code>
 */
public WaitingThread(Condition cond,RouteSpecificPool pool){
  if (cond == null) {
    throw new IllegalArgumentException("Condition must not be null.");
  }
  this.cond=cond;
  this.pool=pool;
}