In Effective Java: item 66, Joshua Bloch gave an example about life failure:
// Broken! - How long would you expect this program to run
class StopThread {
private static boolean stopRequested = false;
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested) {
i++;
}
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
As Joshua Bloch said, this program would not terminate.
But, if I change i++
into System.out.println(i++)
, it terminates successfully!
I can't figure out how it happens!
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
Since you are not telling the thread that stopRequested
is a value that can be modified from outside that thread there are no guarantees that the while
will evaluate to the most recent value of the variable.
This is why the volatile
keyword is useful in this situation, because it will explicitly enforce that stopRequested
value, when read, will be the most recent value set by any thread.
There are further considerations, actually from the point of view of the thread, stopRequested
is a loop invariant, since it is never set by only read, so optimization choices should be considered too: if a value is thought not to be modified then there is no reason to evaluate it on each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With