Singleton mode, 1) a static variable to record a unique instance of the Singlegton class. 2) Private construction method. 3) The GetInstance method instantiates the object and returns the instance.
1, first look at the classic single-case pattern of the wording
1 Public classSingleton {2 Private StaticSingleton instance;3 PrivateSingleton () {4 5 }6 Public StaticSingleton getinstance () {7 if(instance==NULL) {8Instance =NewSingleton ();9 }Ten returninstance; One } A}
It looks like there is no problem, actually, in practice, it is possible to create different instances when the GetInstance method is simultaneously accessed by multithreading.
2, the processing of multi-threaded single-case pattern notation
1 Public classSingleton {2 Private StaticSingleton instance;3 PrivateSingleton () {4 5 }6 Public Static synchronizedSingleton getinstance () {7 if(instance==NULL) {8Instance =NewSingleton ();9 }Ten returninstance; One } A}
By adding the Synchronized keyword to the getinstance method, you can solve the problem of creating different instances caused by multithreading. But synchronization degrades performance, isn't it another problem?
3. Use "eager" to create instances instead of deferring instantiation
1 Public classSingleton {2 Private StaticSingleton instance =NewSingleton ();3 PrivateSingleton () {4 5 }6 Public StaticSingleton getinstance () {7 returninstance;8 }9}
This way, we rely on the JVM to create a unique instance as soon as the class is loaded. The JVM guarantees that this instance must be created before any thread accesses instance. But not recommended. Suggested "deferred instantiation" (Lazy Instantiaze)
4, with "Double check lock", reduce the use of synchronization in the Getinstace (recommended)
1 Public classSingleton {2 //The volatile keyword ensures that when the instance variable is initialized to the singleton instance,3 //multiple threads can handle instance variables correctly4 Private volatile StaticSingleton instance;5 PrivateSingleton () {6 7 }8 Public StaticSingleton getinstance () {9 if(instance==NULL) {Ten synchronized(Singleton.class) { One if(instance==NULL) { AInstance =NewSingleton (); - } - } the } - returninstance; - } -}
Note: 1.4 and earlier versions are not available for double lock
If performance is the focus of your attention, this can help you greatly reduce getinstance time consumption.
Java Singleton mode