When are changes in Synchronized block visible to other threads

末鹿安然 提交于 2019-12-03 12:49:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!