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

后端 未结 4 1489
再見小時候
再見小時候 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:22

    The static initialisation block of any class is guaranteed to be single threaded. A simpler singleton is to use an enum

    enum Singleton {
        INSTANCE;
    }
    

    This is also threads safe and the class lazy-initialised.

提交回复
热议问题