As I was trying to understand better the behaviour of JVM, a issue came up.
I defined a Calculator
thread which calculates a sum and makes the result available through the getTotal() method. The Reader thread keeps a reference to the Calculator and prints the result.
As I wanted the result to the be printed only after the calculation, Reader calls wait() before calling getTotal(). Calculator calls notify() as soon as the result is ready.
In the main method, one Calculator object and three Reader objects are instantiated. The source code is presented below:
Now the curious stuff: as notify() in called just once, at most one Reader thread would print the result. However, the program ended with the following output:
Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45
(Thread-2) total is: 45
(Thread-3) total is: 45
Even if I leave out the line with the notify() call, the output is the same.
The program just worked as I expected after I modified the way the Calculator thread is started, changing
c.start(); to
new Thread(c).start();:
Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45
How is it possible ? I thought the synchronization mechanism was independent of the way threads were created. May I consider this a spurious wakeup ?
Thanks in advance