Generally, the singleton mode can be used in the following two forms.
Eager Mode
Package com. Dayang. design;Public ClassSingleton {PrivateSingleton (){}PrivateStaticSingleton =NewSingleton ();Public StaticSingleton getinstance (){ReturnSingleton ;}} is better, because an object is created at the beginning of loading, and the same object is returned at any time. However, if this singleton object is not used for a long time after the system is started, initialization may be a waste at the beginning.
Package com. Dayang. design;Public ClassSingleton2 {PrivateSingleton2 (){}Private StaticSingleton2 singleton2 =Null;Public Static SynchronizedSingleton2 getinstance (){
If(Singleton2 =Null){Return NewSingleton2 ();}ReturnSingleton2 ;}} in actual operations, if there is no synchronized, more than one object may be generated in concurrency. If synchronized exists, the situation will be better. The disadvantage is that during synchronizationProgramThe efficiency is reduced, so if the synchronization is required every time the object is obtained, the performance will be greatly affected.
Double check
The following mode can be used to solve the problem in JDK or later.
PackageCom. Design. Singleton;
Public ClassSingleton3 {
Private Volatile StaticSingleton3 instance;
PrivateSingleton3 (){}
@ Suppresswarnings ("Unused")
Private StaticSingleton3 getinstance (){
If(Instance =Null){
Synchronized(Singleton3.Class){
If(Instance =Null){
Instance =NewSingleton3 ();
}
}
}
ReturnInstance;
}
}
In this design, the efficiency problem caused by synchronization can be well avoided.
In addition, volatile instructions in the appendix:
when a member variable modified by volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time. In the Java language specification, it is pointed out that in order to get the best speed, the thread is allowed to save private copies of shared member variables, the original value of the shared member variable is compared only when the thread enters or leaves the Code block for synchronization. In this way, when multiple threads interact with an object at the same time, you must notice that the thread needs to get the shared member variable changes in a timely manner. The volatile keyword prompts VM: For this member variable, it cannot store its private copy, but should directly interact with the shared member variable. Suggestion: use volatile on the member variables accessed by two or more threads. You do not need to use this variable when it is already in the synchronized code block or a constant. Because volatile is used to block the necessary code optimization in the VM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.