更新时间:2023-09-18 18:08:46
正如已经指出的,它绝对是线程安全的, 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):
- 从静态初始化程序初始化对象引用;
- 将对其的引用存储到volatile字段或AtomicReference中;
- 将其引用到正确构造的对象的最终字段中;