Thread safety in Singleton

后端 未结 5 1924
庸人自扰
庸人自扰 2020-11-29 23:00

I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

         


        
5条回答
  •  清歌不尽
    2020-11-29 23:17

    Josh Bloch recommends 2 solutions:

    1) worser:

    class Singleton {
    
       public static Singleton instance = new Singleton();
    
       ...
    }
    

    2) better:

    public enum Singleton {
    
       INSTANCE;
    
       ...
    }
    

提交回复
热议问题