Why is this static final variable in a singleton thread-safe?

后端 未结 4 1485
再見小時候
再見小時候 2020-12-15 22:05

Reading this site, I\'ve found this:

[The] line private static final Foo INSTANCE = new Foo(); is only executed when the class is actual

4条回答
  •  被撕碎了的回忆
    2020-12-15 22:31

    It is guaranteed to be thread safe because the JVM guarantees that static initializers are executed on a single thread.

    It doesn't mean that the instance of Foo is internally thread safe- it just means that you are guaranteed that the constructor of Foo will be called exactly once, on one thread, via this particular code path.

提交回复
热议问题