I am reading 《Understanding the JVM Advanced Features and Best practices》 that has a code segment that explains happens-before rule in java. I cannot understand. The code is below:
private int value = 0;
//executed by Thread A
public void setValue(int value){
this.value = value;
}
//executed by Thread B
public void getValue(){
return value;
}
Suppose that thread A
starts before thread B
in code. I can understand that we don't know the result returned by getValue()
in Thread B, because it is not thread safe. But the book says if add synchronized key word to function setValue()
and getValue()
, then there is not exists thread safe problem and method getValue()
will return the right value. The book explains that because synchronized
meets with happens-before rule. So I have two questions by below code.
public class VolatileDemo3 {
private volatile int value = 0;
public static void main(String[] args) {
VolatileDemo3 v = new VolatileDemo3();
Thread A = new Thread(v.new Test1());// Thread A
Thread B = new Thread(v.new Test2());//Thread B
A.start();
B.start();
}
public void setValue(int value){
this.value = value;
}
public int getValue(){
return this.value;
}
public class Test1 implements Runnable {
@Override
public void run() {
setValue(10);
}
}
public class Test2 implements Runnable {
@Override
public void run() {
int v = getValue();
System.out.println(v);
}
}
}
- Although
A.start()
run beforeB.start()
and value isvolatile
, we can't ensure thread B can print out10
, right? Because thread B is possible scheduled first by JVM, then thread B will print 0 not 10. - Even if thread
A
scheduled before threadB
by JVM, but we also can't guarantee that the instructionthis.value = value
executed by JVM beforereturn this.value
because JVM will sort instructions again. Am I understanding is right? Please help me.