Java Code Examples for java.util.concurrent.locks.Condition#await()

The following examples show how to use java.util.concurrent.locks.Condition#await() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiLangsStanfordCoreNLPClient.java    From blog-codes with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * This method creates an async call to the server, and blocks until the server
 * has finished annotating the object.
 */
@Override
public void annotate(Annotation annotation) {
  final Lock lock = new ReentrantLock();
  final Condition annotationDone = lock.newCondition();
  annotate(Collections.singleton(annotation), 1, (Annotation annInput) -> {
    try {
      lock.lock();
      annotationDone.signal();
    } finally {
      lock.unlock();
    }
  });
  try {
    lock.lock();
    annotationDone.await();  // Only wait for one callback to complete; only annotating one document
  } catch (InterruptedException e) {
    log.info("Interrupt while waiting for annotation to return");
  } finally {
    lock.unlock();
  }
}
 
Example 2
Source File: ReentrantLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Awaits condition "indefinitely" using the specified AwaitMethod.
 */
void await(Condition c, AwaitMethod awaitMethod)
        throws InterruptedException {
    long timeoutMillis = 2 * LONG_DELAY_MS;
    switch (awaitMethod) {
    case await:
        c.await();
        break;
    case awaitTimed:
        assertTrue(c.await(timeoutMillis, MILLISECONDS));
        break;
    case awaitNanos:
        long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
        long nanosRemaining = c.awaitNanos(timeoutNanos);
        assertTrue(nanosRemaining > timeoutNanos / 2);
        assertTrue(nanosRemaining <= timeoutNanos);
        break;
    case awaitUntil:
        assertTrue(c.awaitUntil(delayedDate(timeoutMillis)));
        break;
    default:
        throw new AssertionError();
    }
}
 
Example 3
Source File: DatastreamServer.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * The main entry point for Brooklin server application
 *
 * Expects a Java properties configuration file containing the server
 * properties to use for setting up a {@link DatastreamServer} instance.
 */
public static void main(String[] args) throws Exception {
  Properties serverProperties = getServerProperties(args);
  DatastreamServer server = new DatastreamServer(serverProperties);
  ReentrantLock lock = new ReentrantLock();
  Condition shutdownCondition = lock.newCondition();
  // attach shutdown handler to catch control-c
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    lock.lock();
    LOG.info("Starting the shutdown process..");
    server.shutdown();
    shutdownCondition.signalAll();
  }));

  lock.lock();
  server.startup();
  shutdownCondition.await();
  LOG.info("Main thread is exiting...");
}
 
Example 4
Source File: ConcurrentUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Await for condition, handling
 * <a href="http://errorprone.info/bugpattern/WaitNotInLoop">spurious wakeups</a>.
 * @param condition condition to await for
 * @param timeout the maximum time to wait in milliseconds
 * @return value from {@link Condition#await(long, TimeUnit)}
 */
public static boolean await(final Condition condition, final long timeout) throws InterruptedException {
   boolean awaited = false;
   long timeoutRemaining = timeout;
   long awaitStarted = System.currentTimeMillis();
   while (!awaited && timeoutRemaining > 0) {
      awaited = condition.await(timeoutRemaining, TimeUnit.MILLISECONDS);
      timeoutRemaining -= System.currentTimeMillis() - awaitStarted;
   }
   return awaited;
}
 
Example 5
Source File: Misc.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void awaitForCondition(Condition cond) {
  while (true) {
    try {
      cond.await();
      break;
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
      Misc.checkIfCacheClosing(ie);
    }
  }
}
 
Example 6
Source File: FixClientLifecycleTest.java    From nanofix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToStartListeningAgainAfterFirstStartingAndThenStopping() throws InterruptedException
{
    Lock lock = new ReentrantLock();
    final Condition connectionClosedCondition = lock.newCondition();
    final Condition connectionEstablishedCondition = lock.newCondition();

    final FixClient fixClient = FixClientFactory.createFixClient(9990);
    fixClient.registerTransportObserver(new SignallingConnectionObserver(lock, connectionEstablishedCondition, connectionClosedCondition));


    fixClient.listen();

    try
    {
        lock.lock();
        final FixClient fixClient2 = FixClientFactory.createFixClient("localhost", 9990);
        fixClient2.connect();
        final boolean connectionEstablished = connectionEstablishedCondition.await(5, TimeUnit.SECONDS);
        Assert.assertTrue(connectionEstablished);
        fixClient2.killSocket();
        final boolean connectionClosed = connectionClosedCondition.await(5, TimeUnit.SECONDS);
        Assert.assertTrue(connectionClosed);
        fixClient.listen();
    }
    finally
    {
        lock.unlock();
    }
}
 
Example 7
Source File: ConnectionNotificationsIntegrationTest.java    From nanofix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotifyOnConnectionClosed() throws Exception
{
    FixClient fixClient;
    final Lock lock = new ReentrantLock();

    final Condition connectionEstablishedCondition = lock.newCondition();
    final Condition connectionClosedCondition = lock.newCondition();

    byteArrayOutputStream = new ByteArrayOutputStream();
    writableByteChannel = Channels.newChannel(byteArrayOutputStream);
    readableByteChannel = Channels.newChannel(new ByteArrayInputStream(new byte[0]));
    fixClient = FixClientFactory.createFixClient(new IntegrationSocketFactory(readableByteChannel, writableByteChannel));
    fixClient.registerTransportObserver(new SignallingConnectionObserver(lock, connectionEstablishedCondition, connectionClosedCondition));

    try
    {
        //when
        lock.lock();
        fixClient.connect();
        final boolean connectionClosed = connectionClosedCondition.await(5, TimeUnit.SECONDS);
        Assert.assertTrue(connectionClosed);
    }
    finally
    {
        lock.unlock();
    }
}
 
Example 8
Source File: SignalizationBasedEventSynchronizer.java    From bromium with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void awaitUntil(SynchronizationEvent synchronizationEvent) throws InterruptedException, TimeoutException {
    logger.debug("Before await " + synchronizationEvent.isSatisfied());
    if (synchronizationEvent.isSatisfied()) {
        return;
    }

    try {
        lock.lock();

        Condition condition = lock.newCondition();
        eventConditionMap.put(synchronizationEvent, condition);

        logger.debug("When calling await " + synchronizationEvent.isSatisfied());
        boolean timedOut = !condition.await(timeoutInSeconds, TimeUnit.SECONDS);

        if (timedOut) {
            logger.debug("After timeout " + synchronizationEvent.isSatisfied());
            logger.error("Condition {} timed out! ", synchronizationEvent.getName());
            throw new TimeoutException("The synchronization event " + synchronizationEvent.getName() + " was not satisfied in the specified time");
        }
    } finally {
        lock.unlock();
    }

}
 
Example 9
Source File: ThriftHiveMetaStoreCore.java    From beeju with Apache License 2.0 5 votes vote down vote up
public void initialise() throws Exception {
  thriftPort = -1;
  final Lock startLock = new ReentrantLock();
  final Condition startCondition = startLock.newCondition();
  final AtomicBoolean startedServing = new AtomicBoolean();
  try (ServerSocket socket = new ServerSocket(0)) {
    thriftPort = socket.getLocalPort();
  }
  beejuCore.setHiveVar(HiveConf.ConfVars.METASTOREURIS, getThriftConnectionUri());
  final HiveConf hiveConf = new HiveConf(beejuCore.conf(), HiveMetaStoreClient.class);
  thriftServer.execute(new Runnable() {
    @Override
    public void run() {
      try {
        HadoopThriftAuthBridge bridge = new HadoopThriftAuthBridge23();
        HiveMetaStore.startMetaStore(thriftPort, bridge, hiveConf, startLock, startCondition, startedServing);
      } catch (Throwable e) {
        LOG.error("Unable to start a Thrift server for Hive Metastore", e);
      }
    }
  });
  int i = 0;
  while (i++ < 3) {
    startLock.lock();
    try {
      if (startCondition.await(1, TimeUnit.MINUTES)) {
        break;
      }
    } finally {
      startLock.unlock();
    }
    if (i == 3) {
      throw new RuntimeException("Maximum number of tries reached whilst waiting for Thrift server to be ready");
    }
  }
}
 
Example 10
Source File: CallbackTask.java    From jforgame with Apache License 2.0 5 votes vote down vote up
@Override
public Message call() throws Exception {
    try {
        CReqCallBack reqCallBack = (CReqCallBack) request;
        int index = CallBack.nextMsgId();
        reqCallBack.setIndex(index);
        reqCallBack.serialize();

        session.sendMessage(reqCallBack);

        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        long maxTimeOut = 5 * TimeUtil.ONE_SECOND;
        long startTime = System.currentTimeMillis();
        CallBackService callBackService = CallBackService.getInstance();
        while (System.currentTimeMillis() - startTime <= maxTimeOut) {
            CallBack c = callBackService.removeCallBack(index);
            if (c != null) {
                return c.getData();
            }

            try {
                lock.lockInterruptibly();
                condition.await(10, TimeUnit.MILLISECONDS);
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }
        }
    } finally {
        C2SSessionPoolFactory.getInstance().returnSession(session);
    }
    // 超时返回
    return null;
}
 
Example 11
Source File: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 5 votes vote down vote up
/**
 * Inserts the specified element at the tail of this queue with the given priority, waiting for space to become available if the queue is full.
 * 
 * @throws IllegalArgumentException if pItem is <code>null</code>
 * @throws InterruptedException 
 */
public void put(final int pPriority, final T pItem) throws IllegalArgumentException, InterruptedException {
	if (pItem == null) { 
		throw new IllegalArgumentException("pItem must not be null.");
	}

	final ReentrantLock lock = this.mLock;
	final Condition notFullCondition = this.mNotFullConditions.get(pPriority);
	lock.lockInterruptibly();

	try {
		final IList<T> queue = this.mQueues.get(pPriority);
		if (queue == null) {
			throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'.");
		}

		final int queueCapacity = this.mQueueCapacities.get(pPriority);
		try {
			while (queue.size() == queueCapacity) {
				notFullCondition.await();
			}
		} catch (final InterruptedException e) {
			/* Propagate to non-interrupted thread. */
			notFullCondition.signal();
			throw e;
		}
		insert(pPriority, pItem);
	} finally {
		lock.unlock();
	}
}
 
Example 12
Source File: AutomaticWorkQueueTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchedule() throws Exception {
    workqueue = new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE, INITIAL_SIZE,
                                           UNBOUNDED_HIGH_WATER_MARK,
                                           UNBOUNDED_LOW_WATER_MARK,
                                           DEFAULT_DEQUEUE_TIMEOUT);
    final Lock runLock = new ReentrantLock();
    final Condition runCondition = runLock.newCondition();
    long start = System.currentTimeMillis();
    Runnable doNothing = new Runnable() {
        public void run() {
            runLock.lock();
            try {
                runCondition.signal();
            } finally {
                runLock.unlock();
            }
        }
    };

    workqueue.schedule(doNothing, 5000L);

    runLock.lock();
    try {
        runCondition.await();
    } finally {
        runLock.unlock();
    }

    assertTrue("expected delay",
               System.currentTimeMillis() - start >= 4950L);
}
 
Example 13
Source File: MultipointServer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void await(final Condition condition, final long time, final TimeUnit unit) {
    lock.lock();
    try {
        condition.await(time, unit);
    } catch (InterruptedException e) {
        Thread.interrupted();
    } finally {
        lock.unlock();
    }
}
 
Example 14
Source File: LinkedBlockingQueue.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 实现思路:
 *  1、上take锁
 *  2、队空,take操作阻塞
 *  3、队不空,从对头拿一个元素
 *  4、校验队列长度是否大于0,大于则唤醒其他take操作
 *  5、释放take锁
 *  6、校验队列长度是否等于capacity-1,等于则唤醒put操作(这个-1是刚take的,可能有put在阻塞中)
 * @return 元素
 */
@Override
public E take() throws InterruptedException {
    E e;
    int c;

    final ReentrantLock takeLock = this.takeLock;
    final AtomicInteger count = this.count;
    final Condition notEmpty = this.notEmpty;
    // 1、上take锁
    takeLock.lockInterruptibly();
    try {
        // 2、队空,take操作阻塞
        while (count.get() == 0) {//为什么是while,不是if?防止虚假唤醒
            notEmpty.await();
        }
        // 3、队不空,从对头拿一个元素
        e = dequeue();
        c = count.getAndDecrement(); // 次处为旧值,旧值=新值 + 1。为啥是拿旧值?
        // 4、校验队列长度是否大于0,大于则唤醒其他take操作
        if (c > 1) {
            notEmpty.signal();
        }
    } finally {
        // 5、释放take锁
        takeLock.unlock();
    }
    // 6、校验队列长度是否等于capacity-1,等于则唤醒put操作(这个-1是刚take的,可能有put在阻塞中)
    if (c == capacity)
        signalNotFull();
    return e;
}
 
Example 15
Source File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testGetWaitingThreads(boolean fair) {
    final PublicReentrantReadWriteLock lock =
        new PublicReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    final CountDownLatch locked1 = new CountDownLatch(1);
    final CountDownLatch locked2 = new CountDownLatch(1);
    Thread t1 = new Thread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.writeLock().lock();
            assertTrue(lock.getWaitingThreads(c).isEmpty());
            locked1.countDown();
            c.await();
            lock.writeLock().unlock();
        }});

    Thread t2 = new Thread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.writeLock().lock();
            assertFalse(lock.getWaitingThreads(c).isEmpty());
            locked2.countDown();
            c.await();
            lock.writeLock().unlock();
        }});

    lock.writeLock().lock();
    assertTrue(lock.getWaitingThreads(c).isEmpty());
    lock.writeLock().unlock();

    t1.start();
    await(locked1);
    t2.start();
    await(locked2);

    lock.writeLock().lock();
    assertTrue(lock.hasWaiters(c));
    assertTrue(lock.getWaitingThreads(c).contains(t1));
    assertTrue(lock.getWaitingThreads(c).contains(t2));
    assertEquals(2, lock.getWaitingThreads(c).size());
    c.signalAll();
    assertHasNoWaiters(lock, c);
    lock.writeLock().unlock();

    awaitTermination(t1);
    awaitTermination(t2);

    assertHasNoWaiters(lock, c);
}
 
Example 16
Source File: AsyncEndpointTest.java    From RoboZombie with Apache License 2.0 4 votes vote down vote up
/**
 * <p>See {@link #testAsyncSuccess()}.</p>
 */
private void successScenario() throws InterruptedException {
	
	String subpath = "/asyncsuccess", body = "hello";
	
	stubFor(get(urlEqualTo(subpath))
			.willReturn(aResponse()
			.withStatus(200)
			.withBody(body)));

	final Object[] content = new Object[2];
	
	final Lock lock = new ReentrantLock();
	final Condition condition = lock.newCondition();
	
	String result = asyncEndpoint.asyncSuccess(new AsyncHandler<String>() {
		
		@Override
		public void onSuccess(HttpResponse httpResponse, String deserializedContent) {

			lock.lock();
			
			content[0] = httpResponse;
			content[1] = deserializedContent;
			
			condition.signal();
			lock.unlock();
		}
	});

	lock.lock();
	condition.await();
	lock.unlock();

	verify(getRequestedFor(urlEqualTo(subpath)));
	
	assertTrue(content[0] != null);
	assertTrue(content[1] != null);
	assertTrue(content[1].equals(body));
	
	assertNull(result);
}
 
Example 17
Source File: AsyncEndpointTest.java    From RoboZombie with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Tests an erroneous asynchronous request where the implementation of the 
 * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p>
 *  
 * @since 1.3.0
 */
@Test
public final void testAsyncErrorCallbackError() throws InterruptedException {
	
	Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
	
	String subpath = "/errorcallbackerror", body = "non-JSON-content";
	
	stubFor(get(urlEqualTo(subpath))
			.willReturn(aResponse()
			.withStatus(200)
			.withBody(body)));
	
	final Lock lock = new ReentrantLock();
	final Condition condition = lock.newCondition();
	
	asyncEndpoint.asyncErrorCallbackError(new AsyncHandler<User>() {
		
		@Override
		public void onSuccess(HttpResponse httpResponse, User user) {}
		
		@Override
		public void onError(InvocationException error) {
			
			try {
				
				throw new IllegalStateException();
			}
			finally {
				
				lock.lock();
				condition.signal();
				lock.unlock();
			}
		}
	});
	
	lock.lock();
	condition.await();
	lock.unlock();
	
	verify(getRequestedFor(urlEqualTo(subpath)));
	
	successScenario(); //verify that the asynchronous request executor has survived the exception
}
 
Example 18
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testGetWaitingThreads(boolean fair) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch locked1 = new CountDownLatch(1);
    final CountDownLatch locked2 = new CountDownLatch(1);
    Thread t1 = new Thread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            assertTrue(lock.getWaitingThreads(c).isEmpty());
            locked1.countDown();
            c.await();
            lock.unlock();
        }});

    Thread t2 = new Thread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            assertFalse(lock.getWaitingThreads(c).isEmpty());
            locked2.countDown();
            c.await();
            lock.unlock();
        }});

    lock.lock();
    assertTrue(lock.getWaitingThreads(c).isEmpty());
    lock.unlock();

    t1.start();
    await(locked1);

    lock.lock();
    assertHasWaiters(lock, c, t1);
    assertTrue(lock.getWaitingThreads(c).contains(t1));
    assertFalse(lock.getWaitingThreads(c).contains(t2));
    assertEquals(1, lock.getWaitingThreads(c).size());
    lock.unlock();

    t2.start();
    await(locked2);

    lock.lock();
    assertHasWaiters(lock, c, t1, t2);
    assertTrue(lock.getWaitingThreads(c).contains(t1));
    assertTrue(lock.getWaitingThreads(c).contains(t2));
    assertEquals(2, lock.getWaitingThreads(c).size());
    c.signalAll();
    assertHasNoWaiters(lock, c);
    lock.unlock();

    awaitTermination(t1);
    awaitTermination(t2);

    assertHasNoWaiters(lock, c);
}
 
Example 19
Source File: ShowDataDistribution.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
public static void execute(ManagerConnection c, String name) {
    if (!name.startsWith("'") || !name.endsWith("'")) {
        c.writeErrMessage(ErrorCode.ER_YES, "The query should be show @@data_distribution where table ='schema.table'");
        return;
    }
    if (DbleServer.getInstance().getSystemVariables().isLowerCaseTableNames()) {
        name = name.toLowerCase();
    }
    String[] schemaInfo = name.substring(1, name.length() - 1).split("\\.");
    if (schemaInfo.length != 2) {
        c.writeErrMessage(ErrorCode.ER_YES, "The query should be show @@data_distribution where table ='schema.table'");
        return;
    }
    SchemaConfig schemaConfig = DbleServer.getInstance().getConfig().getSchemas().get(schemaInfo[0]);
    if (schemaConfig == null) {
        c.writeErrMessage(ErrorCode.ER_YES, "The schema " + schemaInfo[0] + " doesn't exist");
        return;
    } else if (schemaConfig.isNoSharding()) {
        c.writeErrMessage(ErrorCode.ER_YES, "The schema " + schemaInfo[0] + " is no sharding schema");
        return;
    }
    TableConfig tableConfig = schemaConfig.getTables().get(schemaInfo[1]);
    if (tableConfig == null) {
        c.writeErrMessage(ErrorCode.ER_YES, "The table " + name + " doesn‘t exist");
        return;
    } else if (tableConfig.isNoSharding()) {
        c.writeErrMessage(ErrorCode.ER_YES, "The schema table " + name + " is no sharding table");
        return;
    }
    ReentrantLock lock = new ReentrantLock();
    Condition cond = lock.newCondition();
    Map<String, Integer> results = new ConcurrentHashMap<>();
    AtomicBoolean succeed = new AtomicBoolean(true);
    for (String dataNode : tableConfig.getDataNodes()) {
        OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler(new String[]{"COUNT"}, new ShowDataDistributionListener(dataNode, lock, cond, results, succeed));
        SQLJob sqlJob = new SQLJob("SELECT COUNT(*) AS COUNT FROM " + schemaInfo[1], dataNode, resultHandler, true);
        sqlJob.run();
    }
    lock.lock();
    try {
        while (results.size() != tableConfig.getDataNodes().size()) {
            cond.await();
        }
    } catch (InterruptedException e) {
        c.writeErrMessage(ErrorCode.ER_YES, "occur InterruptedException, so try again later ");
        return;
    } finally {
        lock.unlock();
    }

    if (!succeed.get()) {
        c.writeErrMessage(ErrorCode.ER_YES, "occur Exception, so see dble.log to check reason");
        return;
    }
    ByteBuffer buffer = c.allocate();

    // write header
    buffer = HEADER.write(buffer, c, true);

    // write fields
    for (FieldPacket field : FIELDS) {
        buffer = field.write(buffer, c, true);
    }

    // write eof
    buffer = EOF.write(buffer, c, true);

    // write rows
    byte packetId = EOF.getPacketId();
    Map<String, Integer> orderResults = new TreeMap<>(results);

    for (Map.Entry<String, Integer> entry : orderResults.entrySet()) {
        RowDataPacket row = new RowDataPacket(FIELD_COUNT);
        row.add(StringUtil.encode(entry.getKey(), c.getCharset().getResults()));
        row.add(IntegerUtil.toBytes(entry.getValue()));
        row.setPacketId(++packetId);
        buffer = row.write(buffer, c, true);
    }
    // write last eof
    EOFPacket lastEof = new EOFPacket();
    lastEof.setPacketId(++packetId);
    buffer = lastEof.write(buffer, c, true);

    // post write
    c.write(buffer);
}
 
Example 20
Source File: TestLockProblems.java    From huntbugs with Apache License 2.0 4 votes vote down vote up
@AssertNoWarning("*")
public void waitForConditionOk(Condition cond) throws InterruptedException {
    cond.await();
}