Java – singleton mode
Recently, I asked questions about Java in an interview with the following code. Because I just started using Java and there is almost no code in Java, I really don't know what the following code is
The problem is to choose the worst option described with the following code:
public class Bolton { private static Bolton INST = null; public static Bolton getInstance() { if ( INST == null ) { INST = new Bolton(); } return INST; } private Bolton() { } }
Here are the options for this problem
Which of the following is correct? Why?
Solution
This is a singleton pattern
The idea of singleton pattern has only one instance of the available class Therefore, the constructor is set to private. In this case, the class maintains a getInstance () method, which can either call the existing instance variable Inst in this class or create a new instance variable Inst for the executor. The answer may be 1 because it is not thread safe I may be confused about No. 3, which I have already put down, but it is not a defect in design and technology
The following is an example of Wikipedia's lazy initialization, thread safe singleton mode:
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 allows java to read it from memory without setting it in the cache
Synchronized statements or methods help concurrency
Read more about double checked locking. This is a "lazy initialization" Singleton. What happens