java.util.concurrent.locks.Condition Java Examples

The following examples show how to use java.util.concurrent.locks.Condition. 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: MqttTestClient.java    From diozero with MIT License 6 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
	if (topic.equals(MqttProviderConstants.RESPONSE_TOPIC)) {
		// TODO How to handle different response types?
		DiozeroProtos.Response response = DiozeroProtos.Response.parseFrom(message.getPayload());
		Logger.info("Got response message: {}", response);

		String correlation_id = response.getCorrelationId();
		responses.put(correlation_id, response);

		Condition condition = conditions.remove(correlation_id);
		if (condition == null) {
			Logger.error("No condition for correlation id {}", correlation_id);
		} else {
			lock.lock();
			try {
				condition.signalAll();
			} finally {
				lock.unlock();
			}
		}
	} else {
		Logger.warn("Unrecognised topic {}", topic);
	}
}
 
Example #2
Source File: MultiThreadTest.java    From java-master with Apache License 2.0 6 votes vote down vote up
@Test
public void test7() throws Exception {
    Queue<String> cachePoolQueue = new LinkedList<>();
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition condition = reentrantLock.newCondition();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.submit(() -> {
        Producer2 producer = new Producer2(cachePoolQueue, reentrantLock, condition);
        while (true) {
            producer.produce();
        }
    });
    for (int i = 0; i < 5; i++) {
        executorService.submit(() -> {
            Consumer2 consumer = new Consumer2(cachePoolQueue, reentrantLock, condition);
            while (true) {
                consumer.consume();
            }
        });
    }
    executorService.shutdown();
    TimeUnit.SECONDS.sleep(5);
}
 
Example #3
Source File: AppContext.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor for AppContext.  This method is <i>not</i> public,
 * nor should it ever be used as such.  The proper way to construct
 * an AppContext is through the use of SunToolkit.createNewAppContext.
 * A ThreadGroup is created for the new AppContext, a Thread is
 * created within that ThreadGroup, and that Thread calls
 * SunToolkit.createNewAppContext before calling anything else.
 * That creates both the new AppContext and its EventQueue.
 *
 * @param   threadGroup     The ThreadGroup for the new AppContext
 * @see     sun.awt.SunToolkit
 * @since   1.2
 */
AppContext(ThreadGroup threadGroup) {
    numAppContexts.incrementAndGet();

    this.threadGroup = threadGroup;
    threadGroup2appContext.put(threadGroup, this);

    this.contextClassLoader =
         AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });

    // Initialize push/pop lock and its condition to be used by all the
    // EventQueues within this AppContext
    Lock eventQueuePushPopLock = new ReentrantLock();
    put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
    Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
    put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
 
Example #4
Source File: AppContext.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor for AppContext.  This method is <i>not</i> public,
 * nor should it ever be used as such.  The proper way to construct
 * an AppContext is through the use of SunToolkit.createNewAppContext.
 * A ThreadGroup is created for the new AppContext, a Thread is
 * created within that ThreadGroup, and that Thread calls
 * SunToolkit.createNewAppContext before calling anything else.
 * That creates both the new AppContext and its EventQueue.
 *
 * @param   threadGroup     The ThreadGroup for the new AppContext
 * @see     sun.awt.SunToolkit
 * @since   1.2
 */
AppContext(ThreadGroup threadGroup) {
    numAppContexts.incrementAndGet();

    this.threadGroup = threadGroup;
    threadGroup2appContext.put(threadGroup, this);

    this.contextClassLoader =
         AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });

    // Initialize push/pop lock and its condition to be used by all the
    // EventQueues within this AppContext
    Lock eventQueuePushPopLock = new ReentrantLock();
    put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
    Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
    put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
 
Example #5
Source File: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 6 votes vote down vote up
public void clear() {
	final ReentrantLock lock = this.mLock;
	lock.lock();

	try {
		if (this.mSize > 0) {
			final SparseArray<IList<T>> queues = this.mQueues; 
			final int queueCount = queues.size();
			for (int i = 0; i < queueCount; i++) {
				final int priority = this.mQueues.keyAt(i);

				final IList<T> queue = this.mQueues.valueAt(i);
				queue.clear();

				final Condition notFullCondition = this.mNotFullConditions.get(priority);
				notFullCondition.signal();
			}
			this.mSize = 0;
		}
	} finally {
		lock.unlock();
	}
}
 
Example #6
Source File: ConnectionManagerWatcherThreadTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void testEstablishConnectionNotPossible() throws InterruptedException {
  ReentrantLock lock = new ReentrantLock();
  Condition condition = lock.newCondition();
  ConnectionManager connectionManagerMock = mock(ConnectionManager.class);
  when(connectionManagerMock.tryToEstablishConnection()).thenReturn(false);
  when(connectionManagerMock.getState()).thenReturn(ConnectionState.NEVER_CONNECTED);
  ConnectionManagerWatcherThread sut =
      new ConnectionManagerWatcherThread(lock, condition, connectionManagerMock, 50);
  sut.start();
  Thread.sleep(500);
  assertTrue(sut.isAlive());
  verify(connectionManagerMock, atLeast(2)).tryToEstablishConnection();
  assertEquals(State.TIMED_WAITING, sut.getState());
  killThreadAndVerifyState(sut);
}
 
Example #7
Source File: FirmataI2CDevice.java    From diozero with MIT License 6 votes vote down vote up
@Override
public void onReceive(I2CEvent event) {
	Logger.debug(event);
	Integer register = Integer.valueOf(event.getRegister());
	lock.lock();
	try {
		Condition condition = conditions.get(register);
		if (condition == null) {
			Logger.warn("Got an I2C event for a register ({}) not being monitored", register);
		} else {
			LinkedList<I2CEvent> event_queue = eventQueues.get(register);
			if (event_queue == null) {
				event_queue = new LinkedList<>();
				eventQueues.put(register, event_queue);
			}
			event_queue.addLast(event);
			condition.signalAll();
		}
	} finally {
		lock.unlock();
	}
	event.getRegister();
}
 
Example #8
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testSignalAll(boolean fair, final AwaitMethod awaitMethod) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch pleaseSignal = new CountDownLatch(2);
    class Awaiter extends CheckedRunnable {
        public void realRun() throws InterruptedException {
            lock.lock();
            pleaseSignal.countDown();
            await(c, awaitMethod);
            lock.unlock();
        }
    }

    Thread t1 = newStartedThread(new Awaiter());
    Thread t2 = newStartedThread(new Awaiter());

    await(pleaseSignal);
    lock.lock();
    assertHasWaiters(lock, c, t1, t2);
    c.signalAll();
    assertHasNoWaiters(lock, c);
    lock.unlock();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #9
Source File: EventQueue.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public EventQueue() {
    for (int i = 0; i < NUM_PRIORITIES; i++) {
        queues[i] = new Queue();
    }
    /*
     * NOTE: if you ever have to start the associated event dispatch
     * thread at this point, be aware of the following problem:
     * If this EventQueue instance is created in
     * SunToolkit.createNewAppContext() the started dispatch thread
     * may call AppContext.getAppContext() before createNewAppContext()
     * completes thus causing mess in thread group to appcontext mapping.
     */

    appContext = AppContext.getAppContext();
    pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY);
    pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY);
}
 
Example #10
Source File: EventQueue.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public EventQueue() {
    for (int i = 0; i < NUM_PRIORITIES; i++) {
        queues[i] = new Queue();
    }
    /*
     * NOTE: if you ever have to start the associated event dispatch
     * thread at this point, be aware of the following problem:
     * If this EventQueue instance is created in
     * SunToolkit.createNewAppContext() the started dispatch thread
     * may call AppContext.getAppContext() before createNewAppContext()
     * completes thus causing mess in thread group to appcontext mapping.
     */

    appContext = AppContext.getAppContext();
    pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY);
    pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY);
}
 
Example #11
Source File: EventQueue.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public EventQueue() {
    for (int i = 0; i < NUM_PRIORITIES; i++) {
        queues[i] = new Queue();
    }
    /*
     * NOTE: if you ever have to start the associated event dispatch
     * thread at this point, be aware of the following problem:
     * If this EventQueue instance is created in
     * SunToolkit.createNewAppContext() the started dispatch thread
     * may call AppContext.getAppContext() before createNewAppContext()
     * completes thus causing mess in thread group to appcontext mapping.
     */

    appContext = AppContext.getAppContext();
    pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY);
    pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY);
}
 
Example #12
Source File: ReentrantReadWriteLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testGetWaitQueueLength(boolean fair) {
    final PublicReentrantReadWriteLock lock =
        new PublicReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    final CountDownLatch locked = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.writeLock().lock();
            assertEquals(0, lock.getWaitQueueLength(c));
            locked.countDown();
            c.await();
            lock.writeLock().unlock();
        }});

    await(locked);
    lock.writeLock().lock();
    assertHasWaiters(lock, c, t);
    assertEquals(1, lock.getWaitQueueLength(c));
    c.signal();
    assertHasNoWaiters(lock, c);
    assertEquals(0, lock.getWaitQueueLength(c));
    lock.writeLock().unlock();
    awaitTermination(t);
}
 
Example #13
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 #14
Source File: MultiLock.java    From unitime with Apache License 2.0 6 votes vote down vote up
public Unlock lock(Collection<Long> ids) {
	iLock.lock();
	try {
		if (ids == null || ids.isEmpty()) return new Unlock(ids);
		iLog.debug("Locking " + ids + " ...");
		Condition otherCondition = null;
		while ((otherCondition = hasLock(ids)) != null)
			otherCondition.awaitUninterruptibly();
		Condition myCondition = iLock.newCondition();
		for (Long id: ids)
			iIndividualLocks.put(id, myCondition);
		iLog.debug("Locked: " + ids);
		return new Unlock(ids);
	} finally {
		iLock.unlock();
	}
}
 
Example #15
Source File: ConnectionManagerWatcherThread.java    From rabbitmq-cdi with MIT License 5 votes vote down vote up
ConnectionManagerWatcherThread(ReentrantLock connectionManagerLock,
    Condition noConnectionCondition, ConnectionManager connectionManager,
    long connectRetryWaitTime) {
  this.threadStopper = new ThreadStopper();
  this.connectionManagerLock = connectionManagerLock;
  this.noConnectionCondition = noConnectionCondition;
  this.connectionManager = connectionManager;
  this.connectRetryWaitTime = connectRetryWaitTime;
  this.setDaemon(true);
  this.setName("rabbitmq-cdi connect thread");
}
 
Example #16
Source File: ReentrantReadWriteLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testAwaitLockCount(boolean fair) {
    final PublicReentrantReadWriteLock lock =
        new PublicReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    final CountDownLatch locked = new CountDownLatch(2);
    Thread t1 = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.writeLock().lock();
            assertWriteLockedByMoi(lock);
            assertEquals(1, lock.writeLock().getHoldCount());
            locked.countDown();
            c.await();
            assertWriteLockedByMoi(lock);
            assertEquals(1, lock.writeLock().getHoldCount());
            lock.writeLock().unlock();
        }});

    Thread t2 = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.writeLock().lock();
            lock.writeLock().lock();
            assertWriteLockedByMoi(lock);
            assertEquals(2, lock.writeLock().getHoldCount());
            locked.countDown();
            c.await();
            assertWriteLockedByMoi(lock);
            assertEquals(2, lock.writeLock().getHoldCount());
            lock.writeLock().unlock();
            lock.writeLock().unlock();
        }});

    await(locked);
    lock.writeLock().lock();
    assertHasWaiters(lock, c, t1, t2);
    c.signalAll();
    assertHasNoWaiters(lock, c);
    lock.writeLock().unlock();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #17
Source File: Locks.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 * 等待时间
 *
 * @param condition 信号量
 * @return 是否成功
 */
public static boolean awaitQuiet(final Condition condition) {
    if (condition == null) {
        return false;
    }
    try {
        condition.await();
        return true;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    }
}
 
Example #18
Source File: ReentrantReadWriteLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testGetWaitingThreadsIMSE(boolean fair) {
    final PublicReentrantReadWriteLock lock =
        new PublicReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    try {
        lock.getWaitingThreads(c);
        shouldThrow();
    } catch (IllegalMonitorStateException success) {}
}
 
Example #19
Source File: MultiLock.java    From unitime with Apache License 2.0 5 votes vote down vote up
private Condition hasLock(Collection<Long> ids) {
	if (iAllLocked != null) return iAllLocked;
	for (Long id: ids) {
		Condition c = iIndividualLocks.get(id);
		if (c != null) return c;
	}
	return null;
}
 
Example #20
Source File: LockImpl.java    From HolandaCatalinaFw with Apache License 2.0 5 votes vote down vote up
public synchronized Condition newCondition(String conditionName) {
    ConditionImpl result = conditionMap.get(conditionName);
    if(result == null) {
        result = new ConditionImpl(this, conditionName);
        conditionMap.put(conditionName, result);
    }
    return result;
}
 
Example #21
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAwaitNanos_Timeout(boolean fair) {
    try {
        final ReentrantLock lock = new ReentrantLock(fair);
        final Condition c = lock.newCondition();
        lock.lock();
        long startTime = System.nanoTime();
        long timeoutMillis = 10;
        long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
        long nanosRemaining = c.awaitNanos(timeoutNanos);
        assertTrue(nanosRemaining <= 0);
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
        lock.unlock();
    } catch (InterruptedException fail) { threadUnexpectedException(fail); }
}
 
Example #22
Source File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAwait_Timeout(boolean fair) {
    try {
        final ReentrantReadWriteLock lock =
            new ReentrantReadWriteLock(fair);
        final Condition c = lock.writeLock().newCondition();
        lock.writeLock().lock();
        long startTime = System.nanoTime();
        long timeoutMillis = 10;
        assertFalse(c.await(timeoutMillis, MILLISECONDS));
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
        lock.writeLock().unlock();
    } catch (InterruptedException fail) { threadUnexpectedException(fail); }
}
 
Example #23
Source File: ShowDataDistribution.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
ShowDataDistributionListener(String dataNode, ReentrantLock lock, Condition cond, Map<String, Integer> results, AtomicBoolean succeed) {
    this.dataNode = dataNode;
    this.lock = lock;
    this.cond = cond;
    this.results = results;
    this.succeed = succeed;

}
 
Example #24
Source File: TestStateSystemProvider.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Signal for the next event to be processed. Calling this method makes
 * sense only if {@link #setThrottling(boolean)} has been set to true
 */
public void signalNextEvent() {
    fLock.lock();
    try {
        Condition cond = fNextEventSignal;
        if (cond != null) {
            cond.signalAll();
        }
    } finally {
        fLock.unlock();
    }
}
 
Example #25
Source File: ReentrantLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testGetWaitingThreadsIAE(boolean fair) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final PublicReentrantLock lock2 = new PublicReentrantLock(fair);
    try {
        lock2.getWaitingThreads(c);
        shouldThrow();
    } catch (IllegalArgumentException success) {}
}
 
Example #26
Source File: GridCacheLockImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Interrupt every thread on this node waiting on this lock. */
private synchronized void interruptAll() {
    // First release all threads waiting on associated condition queues.
    if (!conditionMap.isEmpty()) {
        // Temporarily obtain ownership of the lock,
        // in order to signal all conditions.
        UUID tempUUID = getOwnerNode();

        long tempThreadID = currentOwnerThreadId;

        setCurrentOwnerNode(thisNode);

        currentOwnerThreadId = Thread.currentThread().getId();

        for (Condition c : conditionMap.values())
            c.signalAll();

        // Restore owner node and owner thread.
        setCurrentOwnerNode(tempUUID);

        currentOwnerThreadId = tempThreadID;
    }

    // Interrupt any future call to acquire/release on this sync object.
    interruptAll = true;

    // Interrupt any ongoing transactions.
    for (Thread t: getQueuedThreads())
        t.interrupt();
}
 
Example #27
Source File: NettyClientAsync.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResponse(Channel channel, Object msg) {
    if (msg == null) {
        return;
    }

    TaskMessage message = (TaskMessage) msg;
    short type = message.get_type();
    if (type == TaskMessage.BACK_PRESSURE_REQUEST) {
        byte[] messageData = message.message();
        ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE + 1);
        buffer.put(messageData);
        buffer.flip();
        boolean startFlowCtrl = buffer.get() == 1;
        int targetTaskId = buffer.getInt();

        //LOG.info("Received flow ctrl ({}) for target task-{}", startFlowCtrl, targetTaskId);
        if (startFlowCtrl) {
            addFlowControl(channel, targetTaskId);
        } else {
            Pair<Lock, Condition> pair = removeFlowControl(targetTaskId);
            /*if (pair != null) {
                try {
                    pair.getFirst().lock();
                    pair.getSecond().signalAll();
                } finally {
                    pair.getFirst().unlock();
                }
            }*/
        }
    } else {
        LOG.warn("Unexpected message (type={}) was received from task {}", type, message.task());
    }
}
 
Example #28
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testHasWaiters(boolean fair) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch pleaseSignal = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            assertHasNoWaiters(lock, c);
            assertFalse(lock.hasWaiters(c));
            pleaseSignal.countDown();
            c.await();
            assertHasNoWaiters(lock, c);
            assertFalse(lock.hasWaiters(c));
            lock.unlock();
        }});

    await(pleaseSignal);
    lock.lock();
    assertHasWaiters(lock, c, t);
    assertTrue(lock.hasWaiters(c));
    c.signal();
    assertHasNoWaiters(lock, c);
    assertFalse(lock.hasWaiters(c));
    lock.unlock();
    awaitTermination(t);
    assertHasNoWaiters(lock, c);
}
 
Example #29
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 #30
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSignal_IMSE(boolean fair) {
    final ReentrantLock lock = new ReentrantLock(fair);
    final Condition c = lock.newCondition();
    try {
        c.signal();
        shouldThrow();
    } catch (IllegalMonitorStateException success) {}
}