Design Mode: Singleton mode and Design Mode
The Singleton mode is a common mode in software development. Its main function is to ensure that there is always only one class instance object in the system.
There are two advantages:
1. for objects that require frequent use, if they need to be re-created each time, and the content of these objects is the same. This not only improves jvm performance overhead (opening new addresses in the heap, but also reduces GC efficiency), but also reduces code running efficiency. If only one instance object exists in the heap. When using any method, you can directly access this instance object, which greatly improves the system running efficiency.
2. objects can be better maintained. If multiple identical instance objects exist in the system, once the attributes of these instance objects change, to ensure Data Validity and uniqueness, you must notify all instance objects in the system of the same changes. However, when the complexity of the system reaches a certain level, the overhead of maintenance will increase. For example, how do I notify all class instances? Or in the multi-thread scenario, how can we ensure that the attribute statuses of all instance objects are synchronized and modified? The Singleton mode can solve this problem well because only one instance object of this class exists in the system.
The core of the singleton mode is to always return a unique instance through the creation method.
The following describes several implementation methods commonly used in development and their advantages and disadvantages:
The simplest form:
1 public class Singleton 2 { 3 private Singleton() 4 { 5 //do sth 6 7 } 8 9 private static Singleton instance=new Singleton();10 11 public static Singleton getInstance()12 {13 return instance;14 }15 }
In this way, the advantages of the singleton mode are that the implementation logic is simple and easy to read and use. The disadvantage is that the instance uses static fields of the class and is initialized directly. Therefore, when the jvm loads the class, the instance is directly created. However, we may never use this instance. If the do something part of the constructor In the example is a very time-consuming part, it will lead to the initial loading of the class, and the response speed of the system continues to rise, in addition, this object instance will always exist in the jvm heap, resulting in a waste of memory.
Ps some may be hard to understand. Since the jvm loads this class, it means we will use this object. Why is there a scenario where this instance will not be used? Here is an example. For example, if a static field of the class is needed, or the static method or the class is reflected, the jvm will load the class.
To solve this problem, developers later came up with a method for delayed loading:
1 public class Singleton 2 { 3 private Singleton() 4 { 5 //do sth 6 } 7 8 private static Singleton instance = null; 9 10 public static synchronized Singleton getInstance()11 {12 if(instance == null)13 {14 instance=new Singleton();15 }16 return instance;17 }18 }
The reason for adding A synchronous protection to this method is that there may be multiple threads. Thread A first enters the method for obtaining the instance and determines that the instance is null, and then starts to run the constructor, thread B enters the method at the same time. Because the constructor has not finished running, the instance is still null, so thread B still calls the constructor. This destroys the uniqueness of a single instance.
However, Singleton is bound to cause thread waits. Let the constructor of Singleton class run only once for fast speed, but now it is reducing the speed for thread safety. Some people may think that a small synchronization has little impact on performance, but if there is a high concurrency, the last thread wait time is the accumulation of the previous thread wait time, the java program performance optimization book has tried to call the above Code in five threads at the same time, the time consumed is 390 ms, rather than the method of delayed loading (the first method) the time consumption is 0 ms (that is, not 1 ms), and there are many differences between the two.
Without delay, the system may overhead useless. What kind of overhead should the latency be used to ensure thread safety and cause additional overhead?
I personally recommend that you use the first one if it is a server (the client needs to be considered based on the Use scenario. The reason is as follows:
1) The method is simple and error-prone. (I think this is very important. Many people may think it doesn't matter)
2) hardware is getting cheaper now, and it is very cost-effective to change the space for most cases.
3) Most clients are more concerned with the response time of the server during the runtime, rather than the speed at which the server starts. (The statement here is not rigorous)
Even so, we still hope to achieve delayed loading and prevent the thread from waiting. So someone thought of the following method:
1 public class Singleton 2 { 3 private Singleton() 4 { 5 //do sth 6 } 7 8 private static Singleton instance = null; 9 10 public static Singleton getInstance()11 {12 if(instance==null)13 {14 synchronized(Singleton.class)15 {16 if(instance==null)17 {18 instance=new Singleton();19 }20 }21 }22 return instance;23 }24 }
The advantage of doing so is to reduce the thread wait interval to the lowest level, and only increase thread security protection during initial class initialization. If the instance has been created successfully, the thread that obtains the instance again does not need to wait again.
I personally do not recommend this writing because it is awkward and inconvenient to read. Although the double lock is widely used, it still needs to be carefully analyzed during the first reading, after all, there are many other elegant ways to implement Singleton in java.
Ps is not applicable to the java memory model before JDK1.5. This is not due to syntax errors, but to the java memory model itself: in short, due to the optimization of jvm command sequence, this may cause a heap memory to be assigned to the instance before the object is initialized on the heap memory. After the instance variable value is assigned successfully, exit the synchronization code block. The new thread enters the judgment condition and finds that the instance is still not initialized. Therefore, the variable is initialized again. The instance is initiated repeatedly. The volatile keyword was introduced after jdk1.5. We can use this keyword to modify the instance variable to prevent jvm from optimizing this instruction.
So what can we do to solve this problem? Smart people think of using internal classes to save the hold of instances.
1 public class Singleton 2 { 3 private Singleton() 4 { 5 // do sth 6 } 7 8 private static class SingletonInner 9 {10 private static Singleton instance = new Singleton();11 }12 13 public static Singleton getInstance()14 {15 return SingletonInner.instance;16 }17 }
In the above example, there are actually no other two problems. First, we 'd better use delayed loading. The best time for delayed loading is when I really want to use the instance, instead of loading the singleton class. Second, the Singleton has been loaded before use. Don't let me wait.
The static internal class can solve this problem well: 1. When the class is loaded (when static fields and static methods are called), the constructor will not be called to create instances. 2. When an instance is actually needed, the instance is saved in the field of the static internal class, and the static internal class will be loaded at this time, and the single instance class will create an instance <clinit> () method. This form of Singleton is also a kind of Singleton that I like very much. It is not only easy to read, but also makes up for some disadvantages of other Singleton.
Finally, we will introduce a way to solve the singleton problem with the Keyword:
What keywords are born to ensure that an instance is born? This is enumeration.
First look at the code
1 public enum Singleton 2 { 3 instance(); 4 Singleton() 5 { 6 // do sth 7 } 8 9 public final void A()10 {11 12 }13 }
Anyone familiar with enumeration knows that every enumeration item is an instance of this class, and this class cannot create more instances. At the same time, through reflection and deserialization, we can actually break through the singleton restrictions in the previous example, that is, to create multiple instances (though, I have never seen any problems that need to be prevented ). By using enumeration, you can solve these problems through java's own mechanism. This is also a very recommended form by the author of objective java. However, although this book is very popular and highly rated, it is rarely seen in the use of this method.
After talking about this, we should also talk about the disadvantages of the singleton mode:
1. The Singleton mode is not easy to expand. The class constructor is privatized, and the subclass cannot execute the constructor of the parent class.
2. in the development process, for the purpose of ensuring as much as possible, once a single instance is constructed, it can be easily and directly used. A large number of methods are often added to the single instance, in this way, the responsibilities of the singleton class are vague, and many functions cannot be used to determine whether the class is responsible. This violates the basic principles of face objects.