Problems with java Thread
I'm reading book "JAVA THREAD" published by OREILLY.
And on fifth chapter, it gives an example.
one Thread's two method:
private boolean done = false;
public void run()
{
while(!done)
{
foo();
}
}
public void setDone()
{
done = true;
}
it says, the run method will be compiled as machine code:
Begin method run
load register r1 with memory location 0xff12345
Label L1:
Test if register r1 == 1
If true branch to L2
Call method foo
Branch to L1
Label L2:
End method run
setDone method will be compiled like:
Begin method setDone
Store 1 into memory location 0xff12345
End method setDone
And it says " because Run method will never reload 0xff12345 to register r1(in while loop), so setDone method will never lead to run stop.
I'm so puzzled with this. I have test this code on windows platform, run method can stop after another Thread call setDone method !.
but I think "JAVA THREAD" should have error on this, so why ?
If the book says it will happen like that, then the book is wrong.
I think what they meant--and what would be correct to say--is that that is an example of what could happen if you don't synchronize all access to the run variable.
The point is this: Threads can have local copies of variables, that are separate from other threads' local copies and separate from the "master" copy. The spec doesn't define where those local copies live--the implementation can put them anywhere it wants--but the most natural and sensible thing would be to store the local copies in CPU registers, rather than in main mem.
The example the book gave shows what might happen if that VM stores threads' local copies in registers. There's no guarantee that the problem they described will happen, but it could, so you have to guard against it.
You guard against it by declaring that shared variable volatile, which requires that the threads use the master copy rather than their local copies, or by synchronizing every access to that thread. Syncing requires reading from the master copy on entering the sync block (or on first access) and writing out to the master copy upon leaving the sync block.