Search code examples
javamultithreadingwaitnotifyexecutor

Java executors: How to notify a single waiting thread within the executer?


So here is what I'm trying to accomplish:

I have a FixedThreadPool with 5 Threads in it. Those threads just sit there and wait to be notified. When notified, the thread within the pool starts to do stuff.

Now, whenever some triggering event occurs, one and only one waiting thread within the pool must be notified. Is it possible to accomplish this at all?

Here is what I tried, but i get an IllegalMonitorStateException:

public class Server {
    private class WorkerThread implements Runnable{ 
        private Object lock = null;

        WorkerThread(Object lock){
            this.lock = lock;
        }

        public void run() {
            try{
                do{
                    synchronized(lock){
                        wait();
                    }
                    // doSomeThing
                }while(true);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    private ExecutorService executor = null;
    private Object lock = new Object();

    Server() {
        executor = Executors.newFixedThreadPool(5);
        for(int i=0; i<5; i++){
            executor.execute(new WorkerThread(lock));
        }
    }

    public void calledWhenTriggerEventOccurs(){
        synchronized(lock) {executor.notify();}
    }
}

Solution

  • Object.notifyAll notifies all threads waiting on this Object's monitor. Object.notify notifies one (random) thread waiting on the monitor. Is this what you were looking for?