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

The following examples show how to use java.util.concurrent.locks.Condition#signal() . 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: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 6 votes vote down vote up
public void clear(final int pPriority) {
	final ReentrantLock lock = this.mLock;
	lock.lock();

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

		queue.clear();

		final Condition notFullCondition = this.mNotFullConditions.get(pPriority);
		notFullCondition.signal();

		this.mSize -= queueSize;
	} finally {
		lock.unlock();
	}
}
 
Example 2
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 3
Source File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testAwait(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();
            locked.countDown();
            c.await();
            lock.writeLock().unlock();
        }});

    await(locked);
    lock.writeLock().lock();
    assertHasWaiters(lock, c, t);
    c.signal();
    assertHasNoWaiters(lock, c);
    assertTrue(t.isAlive());
    lock.writeLock().unlock();
    awaitTermination(t);
}
 
Example 4
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testAwait(boolean fair) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch locked = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            locked.countDown();
            c.await();
            lock.unlock();
        }});

    await(locked);
    lock.lock();
    assertHasWaiters(lock, c, t);
    c.signal();
    assertHasNoWaiters(lock, c);
    assertTrue(t.isAlive());
    lock.unlock();
    awaitTermination(t);
}
 
Example 5
Source File: ReentrantLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testAwait(boolean fair) {
    final PublicReentrantLock lock = new PublicReentrantLock(fair);
    final Condition c = lock.newCondition();
    final CountDownLatch locked = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            locked.countDown();
            c.await();
            lock.unlock();
        }});

    await(locked);
    lock.lock();
    assertHasWaiters(lock, c, t);
    c.signal();
    assertHasNoWaiters(lock, c);
    assertTrue(t.isAlive());
    lock.unlock();
    awaitTermination(t);
}
 
Example 6
Source File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.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 7
Source File: ReentrantLockTest.java    From openjdk-jdk9 with GNU General Public License v2.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 8
Source File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSignal_IMSE(boolean fair) {
    final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    try {
        c.signal();
        shouldThrow();
    } catch (IllegalMonitorStateException success) {}
}
 
Example 9
Source File: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 5 votes vote down vote up
private T extract(final int pPriority) { // TODO Causes another (potentially unnecessary) lookup for the queue and the condition
	final Condition notFullCondition = this.mNotFullConditions.get(pPriority);

	final IList<T> queue = this.mQueues.get(pPriority);
	final T item = queue.remove(0);
	this.mSize--;

	notFullCondition.signal();

	return item;
}
 
Example 10
Source File: ReentrantLockTest.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCondition() throws InterruptedException {
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    Thread thread = new Thread(new ConditionTask(lock, condition));
    thread.start();
    Thread.sleep(2000);
    lock.lock();
    condition.signal();
    lock.unlock();
}
 
Example 11
Source File: BaseHandlerBuilder.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void subQueryFinished(AtomicInteger subNodes, ReentrantLock lock, AtomicBoolean finished, Condition finishSubQuery) {
    if (subNodes.decrementAndGet() == 0) {
        lock.lock();
        try {
            finished.set(true);
            finishSubQuery.signal();
        } finally {
            lock.unlock();
        }
    }
}
 
Example 12
Source File: FifoMessageQueueTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void singalQueue(FifoMessageQueue queue) throws Exception {
    Field lock = null;
    Field condition = null;
    Class<?> queueType = queue.getClass();

    while (queueType != null && lock == null) {
        try {
            lock = queueType.getDeclaredField("lock");
            condition = queueType.getDeclaredField("condition");
        } catch (NoSuchFieldException error) {
            queueType = queueType.getSuperclass();
            if (Object.class.equals(queueType)) {
                queueType = null;
            }
        }
    }

    assertNotNull("MessageQueue implementation unknown", lock);
    lock.setAccessible(true);
    condition.setAccessible(true);

    ReentrantLock lockView = (ReentrantLock) lock.get(queue);
    Condition conditionView = (Condition) condition.get(queue);

    lockView.lock();
    try {
        conditionView.signal();
    } finally {
        lockView.unlock();
    }
}
 
Example 13
Source File: ReentrantLockTest.java    From openjdk-jdk9 with GNU General Public License v2.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) {}
}
 
Example 14
Source File: ReentrantReadWriteLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testSignal_IMSE(boolean fair) {
    final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
    final Condition c = lock.writeLock().newCondition();
    try {
        c.signal();
        shouldThrow();
    } catch (IllegalMonitorStateException success) {}
}
 
Example 15
Source File: BatcherQueue.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
private void signalAll() {
    for (BatchInfo batch : batches) {
        batch.minTargetTime = 0;
        if (batch.signaller != null) {
            batch.signaller.signal();
        }
    }
    for (Condition cond : freeConditions) {
        cond.signal();
    }
}
 
Example 16
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) {}
}
 
Example 17
Source File: ReentrantLockTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testSignalWakesFifo(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 = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            lock.lock();
            locked1.countDown();
            c.await();
            lock.unlock();
        }});

    await(locked1);

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

    await(locked2);

    lock.lock();
    assertHasWaiters(lock, c, t1, t2);
    assertFalse(lock.hasQueuedThreads());
    c.signal();
    assertHasWaiters(lock, c, t2);
    assertTrue(lock.hasQueuedThread(t1));
    assertFalse(lock.hasQueuedThread(t2));
    c.signal();
    assertHasNoWaiters(lock, c);
    assertTrue(lock.hasQueuedThread(t1));
    assertTrue(lock.hasQueuedThread(t2));
    lock.unlock();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example 18
Source File: JobCreatorHolderTest.java    From android-job with Apache License 2.0 4 votes vote down vote up
@Test
public void createJobSucceedsWhenCreatorListIsModifiedConcurrently() {
    // This test verifies that modifying the list of job-creators while
    // another thread is in the middle of JobCreatorHolder#createJob(String)
    // is safe, in that createJob will finish unexceptionally.
    //
    // We'll test thread-safety by beginning iteration through the
    // job-creator list, then adding another creator while the iterator
    // is active.  If we are thread-safe, then iteration will complete
    // without an exception.
    //
    // To coordinate this, we'll need a custom job creator that blocks
    // until it receives a signal to continue.  A "reader" thread will
    // invoke "createJob", iterating over the list, and blocking. While
    // the reader is blocked, a "mutator" thread will modify the creator
    // list, then signal the reader thread to resume.  Any
    // ConcurrentModificationException will be caught and stored.  When
    // both threads are finished, we can verify that no error was thrown.

    final Lock lock = new ReentrantLock();
    final Condition listModified = lock.newCondition();
    final Condition iterationStarted = lock.newCondition();
    final AtomicReference<Throwable> error = new AtomicReference<>();

    final AtomicBoolean isIteratorActive = new AtomicBoolean(false);

    class BlockingJobCreator implements JobCreator {
        @Override
        public Job create(@NonNull String tag) {
            lock.lock();
            try {
                isIteratorActive.set(true);
                iterationStarted.signal();

                listModified.awaitUninterruptibly();
            } finally {
                lock.unlock();
            }

            return null;
        }
    }

    class Mutator extends Thread {
        @Override
        public void run() {
            waitUntilIterationStarted();

            holder.addJobCreator(mockJobCreator);

            signalListModified();
        }

        private void waitUntilIterationStarted() {
            lock.lock();
            try {
                if (!isIteratorActive.get()) {
                    iterationStarted.awaitUninterruptibly();
                }
            } finally {
                lock.unlock();
            }
        }

        private void signalListModified() {
            lock.lock();
            try {
                listModified.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    class Reader extends Thread {
        @Override
        public void run() {
            try {
                holder.createJob("SOME_JOB_TAG");
            } catch (Throwable t) {
                error.set(t);
            }
        }
    }

    holder.addJobCreator(new BlockingJobCreator());

    Mutator mutator = new Mutator();
    Reader reader = new Reader();

    reader.start();
    mutator.start();

    join(mutator);
    join(reader);

    assertThat(error.get()).isNull();
}
 
Example 19
Source File: Futex.java    From es6draft with MIT License 4 votes vote down vote up
Entry(Condition condition, SharedByteBuffer buffer, int index) {
    this.onWake = () -> condition.signal();
    this.buffer = buffer;
    this.index = index;
}
 
Example 20
Source File: FXUtils.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
/**
 * Invokes a Runnable in JFX Thread and waits while it's finished. Like SwingUtilities.invokeAndWait does for EDT.
 *
 * @author hendrikebbers, original author
 * @author rstein, extension to Function, Supplier, Runnable
 * @param argument function argument
 * @param function transform function that should be executed within the JavaFX thread
 * @param <T> generic for argument type
 * @param <R> generic for return type
 * @return function result of type R
 * @throws Exception if a exception is occurred in the run method of the Runnable
 */
public static <T, R> R runAndWait(final T argument, final Function<T, R> function) throws Exception {
    if (Platform.isFxApplicationThread()) {
        return function.apply(argument);
    } else {
        final AtomicBoolean runCondition = new AtomicBoolean(true);
        final Lock lock = new ReentrantLock();
        final Condition condition = lock.newCondition();
        final ExceptionWrapper throwableWrapper = new ExceptionWrapper();

        final RunnableWithReturn<R> run = new RunnableWithReturn<>(() -> {
            R returnValue = null;
            lock.lock();
            try {
                returnValue = function.apply(argument);
            } catch (final Exception e) {
                throwableWrapper.t = e;
            } finally {
                try {
                    runCondition.set(false);
                    condition.signal();
                } finally {
                    runCondition.set(false);
                    lock.unlock();
                }
            }
            return returnValue;
        });
        lock.lock();
        try {
            Platform.runLater(run);
            while (runCondition.get()) {
                condition.await();
            }
            if (throwableWrapper.t != null) {
                throw throwableWrapper.t;
            }
        } finally {
            lock.unlock();
        }
        return run.getReturnValue();
    }
}