What is a singleton mode:
Ensure that there is at most one instance of a class.
The singleton mode is the simplest one for a better understanding of the pattern.
The problem solving method of Singleton mode in multi-threading.
1, add the synchronization keyword on the getinstance () method.
This approach has a drawback if the singleton class is used in a very large number of applications. That is, call getinstance () This method is a lot of times. Because the steps are very resource-intensive. Each call to the getinstance () method takes one synchronization.
2, in order to solve the above problems and then everyone thought of a further approach. It is in the Singleton class itself first static, first initialized only once, and then to the getinstance () method call back, so call each call getinstance () This method is not synchronized when the singleton object is obtained. Static initialization can be added to final
This approach also has a drawback, if the Singleton class is loaded in the program should be initialized first of all.
3, or to solve the above problem, there is a time-step approach. You're thinking that we want the singleton to be initialized only once, so we need to synchronize, not every time we get this singleton class. So the final solution is.
Double check Lock Method code:
Public classSingleton {Private Static volatileSingleton instance=NULL; //Direct static initialization, so that the getinstance () method can be used without adding synchronized. //private final static Singleton = new Singleton (); //Private Construction Methods PrivateSingleton () {}; Public StaticSingleton getinstance () {//only when the initialization is synchronized, the initial is over, in the call this method will only return the instance is not synchronized. if(instance==NULL){ synchronized(Singleton.class) { if(instance==NULL) {instance=NewSingleton (); } } } returninstance; }}
Java design mode 3-Singleton mode