How to write a Singleton in proper manner?

后端 未结 13 1133
走了就别回头了
走了就别回头了 2020-12-23 12:03

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

    private static Singleton re         


        
13条回答
  •  我在风中等你
    2020-12-23 12:58

    This is because your solution is not threadsafe.

    The modern way is to tie the instance to an enum value:

    enum Singleton {
        INSTANCE;
    }
    

    If you want to use lazy init of the instance then you can use the ClassLoader to guarantee thread safety:

    public class Singleton {
            private Singleton() { }
    
            private static class SingletonHolder { 
                    public static final Singleton INSTANCE = new Singleton();
            }
    
            public static Singleton getInstance() {
                    return SingletonHolder.INSTANCE;
            }
    }
    

    More information on Wikipedia

提交回复
热议问题