In Effective Java: item 66, Joshua Bloch gave an example about life failure:
// Broken! - How long would you expect this program to run
class StopTh
The problem is related to the memory value of the variable stopRequest
.
This variable is not defined as volatile
.
If you have a two processors the inner thread check the value of stopRequest
taken from its registry.
The main thread alter the value of stopRequest
in the registry of the other processor.
So the main thread modify a value of stopRequest
but the thread see only a copy of it that never changes.
Modified after take a look at the source code of PrintStream
(thanks to the commend of ΔλЛ): Using a System.out.print
command will use an explicit synchronized
block to print the value passed to it this will grant that the value of stopRequest
is taken from the main memory and not from the registry of the processor.
Adding a volatile
keyword will inform the JVM to take the value from the main memory instead from the registries of the processors and it solve the problem.
Also using the keyword synchronized
will solve this problem because any variable used in the synchronized block is taken and update the main memory.
Memory model without volatile
(Main thread use Processor 1 and explicit thread use Processor 2)
Processor 1 Processor 2 Main memory
----------- ----------- -----------
false false false
true false true // After setting
//stopRequest to true
Defining stopRequest
as volatile
where all threads read stopRequest
from main memory.
Processor 1 Processor 2 Main memory
----------- ----------- -----------
NA NA false
NA NA true // After setting
//stopRequest to true