Java SE API

Condition.signalAll()

Wake waiting threads to recheck the guarded predicate.

Formal Syntax & Structure

java syntaxjava
void signalAll()

Working Example

Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {    static ThreadPoolExecutor pool(int workers, int capacity) {        return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS,            new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy());    }    static void stop(ExecutorService pool) throws InterruptedException {        pool.shutdown();        try {            if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {                for (Runnable pending : pool.shutdownNow()) {                    if (pending instanceof Future<?> future) future.cancel(false);                }                if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running");            }        } catch (InterruptedException e) {            for (Runnable pending : pool.shutdownNow()) {                if (pending instanceof Future<?> future) future.cancel(false);            }            throw e;        }    }
    static class Mailbox {        private final ReentrantLock lock = new ReentrantLock();        private final Condition changed = lock.newCondition();        private String message;        void publish(String value) throws InterruptedException, TimeoutException {            if (!lock.tryLock(2, TimeUnit.SECONDS)) throw new TimeoutException();            try { message = java.util.Objects.requireNonNull(value); changed.signalAll(); }            finally { lock.unlock(); }        }        String receive() throws InterruptedException, TimeoutException {            if (!lock.tryLock(2, TimeUnit.SECONDS)) throw new TimeoutException();            try {                long left = TimeUnit.SECONDS.toNanos(2);                while (message == null) {                    if (left <= 0) throw new TimeoutException();                    left = changed.awaitNanos(left);                }                return message;            } finally { lock.unlock(); }        }    }    public static void main(String[] args) throws Exception {        Mailbox box = new Mailbox();        ThreadPoolExecutor workers = pool(1, 1);        try {            Future<String> reply = workers.submit(box::receive);            box.publish("ready");            System.out.println(reply.get(3, TimeUnit.SECONDS));        } finally { stop(workers); }    }}
Java Reference