The implementation of the Singleton mode is summarized as follows:
The first way: the method of obtaining the instance synchronously, multithreading security, lazy mode. Initialize at the moment the instance is invoked.
Public classSingleton1 {Private StaticSingleton1 instance =NULL; PrivateSingleton1 () {} Public Static synchronizedSingleton1 getinstance () {if(Instance = =NULL) {instance=NewSingleton1 (); } returninstance; }}
The first way: a hungry man mode, thread-safe, but slow loading. The object information was initialized at the moment the class was loaded.
Public class Singleton2 { // class Loads the moment it creates a unique instance privatestaticnew Singleton2 (); Private Singleton2 () { } publicstatic Singleton2 getinstance () { return instance;} }
The Third way: Double check lock mode, only at the time of the first creation of the mutual exclusion check, empty to create the object.
Public classSingleton3 {//the use of volatile after JDK 1.5 to initialize the instance ensures that multithreading is handled correctly Private Static volatileSingleton3 instance =NULL; PrivateSingleton3 () {} Public StaticSingleton3 getinstance () {if(Instance = =NULL) { synchronized(Singleton3.class) { if(Instance = =NULL) {instance=NewSingleton3 (); } } } returninstance; }}
Summary of Java Singleton patterns