Is DCL still broken?

前端 未结 2 1787
清歌不尽
清歌不尽 2021-01-14 21:35

As far as I understand with old JMM the DCL (Double checked Locking) trick to implement lazy singletone was broken, but i tought that it was fixed with new JMM and volatile

2条回答
  •  遥遥无期
    2021-01-14 21:53

    It was fixed in Java 5.

    However these days the "correct" (i.e. the simplest) way is to use an enum for lazy initialization.

    public enum Singleton {
        INSTANCE;
    
        // No need for a getInstance() method
        //public static Singleton getInstance() {
        //    return INSTANCE;
        //}
        // Add methods to your liking
    }
    

提交回复
热议问题