I have read following article from SO
Difference between synchronization of field reads and volatile
here questioner writes
the point of the synchronization is to ensure that the value of acct.balance that are read by this thread is current and that any pending writes to the fields of the object in acct.balance are also written to main memory.
most popular answer:
You are correct.
please research this code:
public class VolatileTest {
static/* volatile */boolean done = false;
public VolatileTest() {
synchronized (this) {
}
}
public static void main(String[] args) throws Exception {
Runnable waiter = new Runnable() {
public void run() {
while (!done)
;
System.out.println("Exited loop");
}
};
new Thread(waiter).start();
Thread.sleep(100); // wait for JIT compilation
synchronized (VolatileTest.class) {
done = true;
}
System.out.println("done is true ");
}
}
On my pc this program doesn't terminate.
Thus I think that
- if I change volatile variable I will see actual value in another thread for any outstanding everywhere!
- if I change variable in synchronized section with monitor "A" I will see actual value only in synchronized section with monitor "A"(for example in another thread)
Am I correct ?