Singleton pattern interview

前端 未结 8 2174
忘了有多久
忘了有多久 2021-02-04 14:26

I am recently asked about java related question in an interview with following code, since I am very new to java and barely code in Java so I really have no idea what the follow

8条回答
  •  [愿得一人]
    2021-02-04 14:34

    This is a Singleton Pattern

    The idea of a Singleton Pattern is to only have one available instance of a class. Therefore the constructor is set to private and the class maintains, in this case, a getInstance() method that either calls an existing instance variable, INST in this class, or creates a new one for the executing program. The answer is probably 1, because it's not thread safe. It may be confused for 3, which I had put down earlier, but that is by design, technically, so not actually a flaw.

    Here's an example of Lazy Initialization, thread-safe singleton pattern from Wikipedia:

    public class SingletonDemo {
    
        private static volatile SingletonDemo instance = null;
    
        private SingletonDemo() {  } 
    
        public static SingletonDemo getInstance() {
            if (instance == null) {
                synchronized (SingletonDemo.class){
                    if (instance == null) {
                        instance = new SingletonDemo();
                    }
                }
            }
            return instance;
        }
    
    }
    

    Setting the instance variable to volatile tells Java to read it from memory and to not set it in cache.

    Synchronized statements or methods help with concurrency.

    Read more about double checked locking which is what happens for a "lazy initialization" singleton

提交回复
热议问题