且构网

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

Java 静态初始值设定项线程安全吗?

更新时间:2023-09-18 16:28:04

是的,Java 静态初始值设定项是线程安全的(使用您的第一个选项).

Yes, Java static initializers are thread safe (use your first option).

但是,如果您想确保代码恰好执行一次,则需要确保该类仅由单个类加载器加载.每个类加载器执行一次静态初始化.

However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.