gurpeet singh wrote:i i think this is happening because of thread cache.
T. Adams wrote:Hi,
Does somebody know why in the following code k2 can be greater than k1? (a sample output: k1: 365731 k2: 365898). Example is a revised version of Mughal book question 13.13.
Thanks,
Seetharaman Venkatasamy wrote:I think helen ma post seems to be interesting... so my question is that cpu scheduler can take thread out from synchronized block ?
Helen Ma wrote: thread 1 and 2 are comparing k1 and k2, k1 and k2 are the two variables shared by them. It's because K1 and k2 are static instances of the class. So, in theory, thread 1 and thread 2 are "looking at" the same data.
How can this happen "thread 1 and thread 2 will do an unsynchronized comparision and got k2> k1"?
Helen Ma wrote:Hi, Gauranghumar,
When thread 1 and 2 are comparing k1 and k2, k1 and k2 are the two variables shared by them. It's because K1 and k2 are static instances of the class. So, in theory, thread 1 and thread 2 are "looking at" the same data.
How can this happen "thread 1 and thread 2 will do an unsynchronized comparision and got k2> k1"?
The key point is that only the synchronized block is protected. As long as one thread isn't blocked, there's the possibility of control passing between them at any time.
Hey I checked your mail
Independent statements within synchronized blocks can anytime be reordered by JIT
This is done for performance optimization
Please refer statement reordering in Java
So even if you add a system.out printing both variables inside the synchronized block will create dependency and eliminate statement reordering....
Thats the reason when there is a relation b/w variables accessed by multiple threads both read & writes should be synchronized
read this:http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.3.1.4
Also look at happens-before in hava
Don't get me started about those stupid light bulbs. |