Waiting for an event in Java - how hard is it? Waiting for an event in Java - how hard is it? multithreading multithreading

Waiting for an event in Java - how hard is it?


It is standard practice to change some state when performing notifyAll and to check some state when performing wait().

e.g.

boolean ready = false;// thread 1synchronized(lock) {    ready = true;    lock.notifyAll();}// thread 2synchronized(lock) {    while(!ready)         lock.wait();}

With this approach, it doesn't matter if thread 1 or thread 2 acquires the lock first.

Some coding analysis tools will give you a warning if you use notify or wait without setting a value or checking a value.


You could use a wait() with timeout, in which case you are not risking to wait forever. Also note that wait() may return even if there was no notify() at all, so, you'll need to wrap your wait inside some conditioned loop. That's the standard way of waiting in Java.

synchronized(syncObject) {    while(condition.isTrue()) {        syncObject.wait(WAIT_TIMEOUT);    }}

(in your Thread 2)

Edit: Moved synchronized outside the loop.


The simplest way is just to say

firstThread.join();

This will be blocking until the first thread is terminated.

But you can implement the same using wait/notify. Unfortunately you have not posted your real code fragments but I guess that if wait does not exit when you call notify it happens because you did not put both into synchronized block. Pay attention that the "argument" of synchronized block must be the same for wait/notify pair.