I was trying examples from JCIP and Below program should not work but even if I execute it say 20 times it always work which means ready
and number
are
This program is broken since ready
and number
should be declared as volatile
.
Due to the fact that ready
and number
are primitive variables, operations on them are atomic but it is not guaranteed that they will be visible by other threads.
It seems that the scheduler runs the threads after main
and that is why they see the number
and ready
being initialized. But that is just one scheduling.
If you add e.g. a sleep
in main
so as to affect the scheduler you will see different results.
So the book is correct, there is no guarantee whether the Runnable
s running in separate threads will ever see the variable's being updated since the variables are not declared as volatile
.
Update:
The problem here is that the due to the lack of volatile
the compiler is free to read the field ready
just once, and reuse the cached value in each execution of the loop.
The program is inherently flawed. And with threading issues the problem usually appears when you deploy your application to the field....
From JSL:
For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:
while (!this.done)
Thread.sleep(1000);The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if an other thread changed the value of this.done.