开发者

Behaviour of synchronized

I have read that code inside a synchronized block conform to 'happens before' semantics so that all the values written inside a synchronized block should be visible to other threads in succession. Furthermore I have read that caches are only flushed with the termination of synchronized block. How would above semantic of 'happens before' be enforced in the scenario described below if only caches are flushed with the synchronized block termination?

Thread A has a reference to object C and changes a field of C in its synchronized code synchronized on C. Thread B also has got a reference to object C. Now thread A is suspended before the synchronized code is finished. Thread B jumps in to action and access object C's field in code with no synchronization on C.

Now is thread B guaranteed to see the changes made by Thread开发者_JAVA技巧 A?


The points is that thread B should be using a synchronized block too, synchronizing on the same monitor as thread A.

If thread B isn't using any synchronization, the changes may or may not be seen.


In addition to the existing answer, note that happens-before(X,Y) only guarantees that Y sees updates by X, not that other threads will see results of X before results of Y.

(In fact, you don't need to be inside a synchronized block to have happens-before relationships between actions in succession inside a single thread. See the first bullet of 17.4.5 in the JLS.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜