开发者

When are changes in Synchronized block visible to other threads

Say that I update values of two variables in a synchronized method. Would it be possible that the new values set in synchronized method be visible to other threads before exiting the synchronized block?

public synchronized void setValues(){
    a=5;
    // assume thread is preempted after this assignment
    // would the value 5 be visible to oth开发者_开发问答er threads?
    // my understanding is that the values will not be flushed to
    // main memory until the lock is released- i.e., until the synchronized
    // method is complete. So the changes will not be visible to other 
    // threads even when not using synchronization
    b=10;
}

Below method is not synchronized, so I understand that the thread may see stale values. My question is if the thread is preempted after assignment to a, is it ever possible that the new value "5" for variable a be visible in printValues method?

public void printValues() {
    System.out.println(a + " " + b);
}


Yes, changes made within synchronized can (but aren't guaranteed) to be visible before you get to the end of the synchronized block. Basically, you usually need to synchronize (on the same lock) when reading or writing data in order to get a consistent view of the world.

The guarantees provided for synchronization are to make "doing the right thing" (synchronizing appropriately) work correctly - they don't guarantee that changes are made atomically when you're not doing the right thing (observing the shared variables without synchronizing).

You can (to some extent) think of the writes within the synchronized block as being like calls to OutputStream.write() with the exit of the synchronized block being like a flush() call. When you're half way through the block, some of the data you've written may have made it to the output file (or whatever) - but it might still be buffered. That's not meant to be an indication of how the memory model is implemented, just an analogy to help you understand how the visibility isn't guaranteed.


The synchronized doesn't guarantee that value of a will be flushed immediately. It will be if a is volatile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜