The wait, notify & notifyAll Methods
Let's assume we have 2 threads: thread 0 that calculates a value and places it in variable 'a', and thread 1 that, when variable 'a' is updated, displays it in the graphical interface of a program. A possible implementation for the function of thread 0, in pseudocode, would be:
function_thread_0:
noua_valoare = calculeaza_valoare_a()
mutex_a.lock()
a = noua_valoare
mutex_a.unlock()
A possible implementation for the function of thread 1, in pseudocode, could be:
function_thread_1:
while(a nu s-a actualizat):
mutex_a.lock()
if (a s-a actualizat):
afiseaza(a)
a = -1 // Resetting the value of 'a'.
mutex_a.unlock()
We observe an issue with this approach: thread 1 will cycle through the while loop multiple times, even if thread 0 does not update 'a', unnecessarily occupying CPU time. This approach is known as busy waiting. While busy waiting is not always a bad idea, in this case, let's assume that it takes a long time for thread 0 to calculate the new value of 'a'. Thus, there is a better solution provided by Java primitives wait(), notify(), and notifyAll().
wait() - forces the current thread to enter a waiting state until another thread calls notify() or notifyAll() on the same object. To make this happen, the current thread must own the monitor of that object. Ownership of the monitor can occur in the following situations:
- A synchronized method on that object has been executed.
- A synchronized block on that object has been executed.
- A synchronized static method on the class to which the object belongs has been executed.
Avoid using wait() on globally visible (static) objects or on constant value Strings (e.g., String myMonitorObject = "";) because the JVM internally optimizes access to such variables, having only one instance throughout the program.
notify() - randomly selects a waiting thread (called wait()) on the same object and transitions it from a waiting state to a running state.
notifyAll() - transitions all waiting threads (those that called wait()) on the same object from a waiting state to a running state.
CheatSheet Wait-Notify