Here's how you implement a condition variable in Java:
synchronized (this) { while (true) { try { wait(); if (someCondition) { break; } } catch (InterruptedException ex) {
The wait call waits until some other thread does notify on this , presumably to say that the condition is now true. However, it is possible that the condition became false before the current thread woke up or that several threads were woken up. (Obviously, this depends on the application logic of what causes notify or notifyAll .) So, we (re) check the condition and repeat if this is not true. This is the while (true) point.
The wait() call must be made inside the monitor lock on this , and it is assumed that this lock protects the state that someCondition checks.
Another tricky thing is related to InterruptedException , which can be thrown by wait() . Some people think this is normal, just crush it. In fact, the right thing is to either distribute it or call Thread.interrupt() to set the interrupted flag again and stop everything that the current thread is doing. If you do not, the thread effectively ignores interrupts ... which is bad.
FWIW - catching an Exception , not an InteruptedException - this is bad practice and possibly a mistake.
source share