Singleton mode: There is only one instance of an object in the context.
Application scenario: thread pool, cache, etc. a system requires only one scene.
Three common single-case modes:
1. Lazy Loading
publicclass Singleton { privatestatic Singleton uniqueInstance; privateSingleton() {} publicstaticgetInstance() { ifnull) new Singleton(); return uniqueInstance; }}
The time taken is obtained by invoking the static method of the class:
Singleton Singleton =singleton.getinstance ();
There is a problem: Multithreading synchronization issues
Multi-threaded when the object is first generated, there is the possibility of executing the IF (uniqueinstance = = null) judgment at the same time, thereby simultaneously multiple new instances
Improved:
publicclass SynSingleton { privatestatic SynSingleton uniqueInstance; privateSynSingleton() {} publicstaticgetInstance() { ifnull) new SynSingleton(); return uniqueInstance; }}
This enables synchronization by synchronized blocks of code.
2. The urgency of instantiation
Each time the method gets the object, it has to do the synchronous synchronized operation, the cost is large, and the synchronization operation is only valid at the first new time (then each call does not do the new operation, the equivalent of read-only not write), so it can be the new object when the class is loaded, and then does not do the new operation. Improvements are as follows:
publicclass UrgSingleton { privatestaticnew UrgSingleton(); privateUrgSingleton() {} publicstaticgetInstance() { return uniqueInstance; }}
The advantages and disadvantages of deferred instantiation and eager instantiation are also obvious:
If this object is expensive, and the whole process is not utilized, the objects that are eagerly instantiated are consumed in vain by the resources.
and delay the instantiation of the synchronization problem, there is a large overhead situation, so there is the following double check lock mode.
3. Double check and lock
Public classDoublesynsingleton {Private Static volatileDoulesynsingleton uniqueinstance;Private Doublesynsingleton() {} Public StaticDoublesynsingletongetinstance() {if(Uniqueinstance = =NULL) {synchronized (Doublesynsingleton.class) {if(Uniqueinstance = =NULL) Uniqueinstance =NewDoublesynsingleton (); } }returnUniqueinstance; }}
As shown above, the synchronized method is used only when the first new object is taken, and then when the object instance is obtained, the exit is completed after the outer if (uniqueinstance = = NULL) Decision, not the subsequent synchronization code block. In this way, performance is improved.
Singleton mode Singleton in Java