且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 并发:final 字段(在构造函数中初始化)是线程安全的吗?

更新时间:2023-09-18 19:39:22

正如已经指出的那样,它绝对是线程安全的,并且 final 在这里很重要,因为它具有内存可见性效果.

As already pointed out it's absolutely thread-safe, and final is important here due to its memory visibility effects.

final 的存在保证其他线程在构造函数完成后可以在没有任何外部同步的情况下看到映射中的值.没有 final 就不能保证在所有情况下都可以,并且在使新构造的对象可用于其他线程时,您将需要使用 安全发布习惯用法,即(来自 Java 并发实践):

Presence of final guarantees that other threads would see values in the map after constructor finished without any external synchronization. Without final it cannot be guaranteed in all cases, and you would need to use safe publication idioms when making newly constructed object available to other threads, namely (from Java Concurrency in Practice):

  • 从静态初始化器初始化对象引用;
  • 将对其的引用存储到可变字段或 AtomicReference 中;
  • 将对其的引用存储到正确构造的对象的最终字段中;或
  • 将对其的引用存储到由锁适当保护的字段中.