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.
What is important to keep in mind is that a broken concurrent program might always work with the right combination of JVM's options, machine architecture etc. That does not make it a good program, as it will probably fail in a different context: the fact that no concurrency issue shows up does not mean there aren't any.
In other words, you can't prove that a concurrent program is correct with testing.
Back to your specific example, I see the same behaviour as what you describe. But, if I remove the Thread.yield()
instruction in the while loop, 3 out of 8 threads stop and print 42, but the rest don't and the program never ends.