Java synchronized 保证可见性

Java juc About 743 words

原因

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

Views: 1,899 · Posted: 2021-09-03

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh