Java Engineering Optimization-singleton mode under multiple threads
When I first learned the design model, I was excited for the excellent design idea. In the future project, I integrated the design model multiple times. In the current design, we have been aware of the foresight of the original design model, but there are also some shortcomings that need to be improved. Some people have said that there is no absolute thing in the world, of course, simple things, the environment has changed and will change. Today we will share with you the optimization of the multi-threaded single-instance model.
1. Traditional
First, let's review how the traditional Singleton (lazy) works:
public class SingletonClass{ private static SingletonClass instance=null; public static SingletonClass getInstance() { if(instance==null) { instance=new SingletonClass(); } return instance; } private SingletonClass(){ }}
We can easily see that common code may be annoying during multi-threaded execution. You can see the image of multi-threaded code running:
2. Double Lock
We can see that thread 1 and thread 2 both execute code ②. what we get is not a singleton object, but multiple objects. We have optimized synchronization.
public static class Singleton{ private static Singleton instance=null; private Singleton(){ //do something } public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(null==instance){ instance=new Singleton(); } } } return instance; }}
We are looking at the multi-thread running diagram of this Code:
As you can see, ③ is only executed once, not only because it is protected by the synchronization mechanism, but also because of its dual judgment, so as to ensure the normal operation of the multi-thread ordering instance mode.
3. Enumeration
After jdk1.5, java noticed this detail. When creating a singleton application, we can use the enumeration type to complete our work, and it is thread-safe.
Source code:
public enum SingletonEnum{ INSTANCE; private String name; publicString getName() { returnname; } publicvoid setName(String name) { this.name = name; } }
This kind of optimization makes code more elegant, but it also brings about some problems, that is, we have a vague concept of object types, so at work, we recommend that you retain the double lock mode. For some tool classes, you can use Enumeration type optimization to simplify our code and logic.
Summary:
The optimization of details is like carving a piece of work of art. The more people we come into contact with, the more strong such ideas we have. Therefore, we often judge the character and quality of a person's affairs, through his contacts, his friends can speculate, and in the computer, we have more excellent frameworks, and we are naturally excellent designers!