DCL, double check lock, central defender. In fact, the DCL many people in a single case mode used, LZ interview people also want them to write, but a lot of people will write wrong. Why would they write it wrong? Where is the source of the error? What are the solutions? The following is an analysis with the LZ.
Problem analysis
Let's look at the lazy type in the singleton pattern:
Public Class Singleton { Private Static SingletonSingleton; Private Singleton () {} public static< Span class= "PLN" > singleton Getinstance () { if (singleton == null) { Singleton = new singleton (); } return Singleton }} /span>
We all know that this is wrong, because it does not guarantee the security of the thread. The optimizations are as follows:
Public Class Singleton { Private Static SingletonSingleton; Private Singleton(){} public static singleton Getinstance () { Span class= "PLN" > if (singleton == null) { Singleton = new singleton (); } return Singleton }} /span>
Optimization is very simple, is the GetInstance method above synchronization, but synchronized will lead to this method is relatively inefficient, resulting in program performance degradation, then how to solve it? Smart people think of the double-check DCL:
Public Class Singleton { Private Static SingletonSingleton; Private Singleton(){} Public Static SingletonGetInstance(){ If(Singleton== Null){ 1 Synchronized (Singleton.Class) { //2 if (singleton == null< Span class= "pun" >) { //3 Singleton = new singleton (); //4 } } } return Singleton;< Span class= "PLN" > }}
As shown above, this code looks perfect for the following reasons:
- If checking the first singleton is not NULL, the following lock action is not required, which greatly improves the performance of the program;
- If the first singleton is null, even if there are multiple threads at the same time, but because of the presence of synchronized, only one thread will be able to create the object;
- When the first thread that acquires the lock is created after the Singleton object is finished, the other singleton must not be null for the second judgment, and the singleton object that has been created is returned directly;
Through the above analysis, the DCL looks really perfect, but can tell you clearly that this is wrong. The logic above is really no problem, the analysis is right, but there is a problem, then where is the problem? Before we answer this question, let's go over the process of creating objects and instantiating an object into three steps:
- Allocating memory space
- Initializing objects
- Assigns the address of the memory space to the corresponding reference
However, as a result of reordering, steps 2 and 3 may be reordered, as follows:
- Allocating memory space
- Assigns the address of the memory space to the corresponding reference
- Initializing objects
If the reordering of 2 and 3 results in a second error, Singleton! = NULL, but it is simply an address, and the object is not initialized, so the return singleton object is an object that is not initialized, as follows:
As shown in the previous illustration, thread B accesses a singleton object that is not initialized.
From the above, we can judge the cause of the DCL's error lies in step 4:
=NewSingleton();
Know the root of the problem, then how to solve it? There are two solutions:
- Reordering of steps 2 and 3 is not allowed during initialization.
- Allow steps 2, 3 in the initialization phase to reorder, but not allow other threads to "see" this reordering.
Solution Solutions
The solution is based on the above two solutions.
Volatile based solutions
For the DCL above, you only need to make a little change: Singleton the variable to life as volatile:
Public Class Singleton { Ensure security with volatile keywords Private Volatile Static SingletonSingleton; Private Singleton(){} Public Static SingletonGetInstance(){ If(Singleton== Null){ Synchronized (singleton. Class if (singleton Span class= "pun" >== null) { Singleton = new singleton (); } } }< Span class= "PLN" > return Singleton; }}
When Singleton is declared volatile, step 2, Step 3 will not be re-ordered, you can solve the above problem.
Class-Based initialization solutions
The root of the solution is to use the Classloder mechanism to ensure that there is only one thread in the initialization of instance. The JVM acquires a lock during the class initialization phase, which synchronizes the initialization of multiple threads to the same class .
Public Class Singleton { Private Static Class Singletonholder{ public static singleton Singleton = new< Span class= "PLN" > singleton (); } public static singleton Getinstance () { Span class= "KWD" >return singletonholder. Singleton; }} /span>
The essence of this solution is to run Step 2 and step 3 reorder, but not allow other threads to see.
The Java language stipulates that for each class or interface C, there is a unique initialization lock LC corresponding to it. The mapping from C to LC is implemented freely by the specific implementation of the JVM. The JVM acquires this initialization lock during the class initialization phase, and each thread acquires at least one lock at a time to ensure that the class has been initialized.
Resources
- Fang Fei: "The Art of Java concurrent programming"
Analysis of DCL from JMM angle of Java memory model