wait(), notify(), notifyAll() in Java

By | 2017-08-12
  • use same object for calling wait() and notify() method, every object has its own lock so calling wait() on objectA and notify() on object B will not make any sense.
  • by calling notify(), the awakened thread will not be able to proceed until the current thread relinquishes the lock on this object.
  • before calling wait(), you should get the lock of the object using synchronized.
  • Always call wait() method in loop because if multiple threads are waiting for lock and one of them got lock and reset the condition and other thread needs to check the condition after they got wake up to see whether they need to wait again or can start processing.
  • A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. So always use this:
synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         … // Perform action appropriate to condition
     }
A lock object:
public class SyncronizeObj {
public void doWait(long l){
    synchronized(this){
        try {
            this.wait(l);
        } catch(InterruptedException e) {
        }
    }
}
public void doNotify() {
    synchronized(this) {
        this.notify();
    }
}
public void doWait() {
    synchronized(this){
        try {
            this.wait();
        } catch(InterruptedException e) {
        }
    }
}
}