Since Java offers the ability to have multiple threads running in a program, there are occasions when we need to restrict the access (synchronize) so that only one thread can access parts of our code at any given time. Java provides the synchronized keyword that accomplishes this goal of serial access. But using synchronized
has some issues. First, if we need to call wait()
on a thread, we must remember to use a while
loop:
while(someCondition){ try { wait(); } catch (InterruptedException e) { //In this case we don't care, but we may want //to propagate with Thread.interrupt() } }
Second, if we have more than one condition that can cause a thread to go into a wait state, we must call notifyAll()
, as we don't have the ability to notify threads for specific conditions. Using notifyAll()
instead of notify()
is less desirable due to the thrashing effect it has of waking up all the threads to compete for a lock when only one will do so. Java 5 introduced...