Java synchronized 保证可见性

Java Lock juc 大约 743 字

原因

synchronized在代码块执行结束后会将执行结果刷新到主存中。

所以synchronized也和volatile有可见性的作用。

JMM 规范

synchronized在可见性上和volatile作用一致。

Doug Lea原文节选:

In terms of atomicity, visibility, and ordering, declaring a field as volatile is nearly identical in effect to using a little fully synchronized class protecting only that field via get/set methods, as in: Declaring a field as volatile differs only in that no locking is involved. In particular, composite read/write operations such as the "++'' operation on volatile variables are not performed atomically.

final class VFloat {
  private float value;

  final synchronized void  set(float f) { value = f; }
  final synchronized float get()        { return value; }
}

引用段落出处

http://gee.cs.oswego.edu/dl/cpj/jmm.html

阅读 147 · 发布于 2021-09-03

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批