Java design mode-singleton Mode
In the 23 GoF design modes, the singleton mode is relatively simple. However, sometimes the simpler the things, the more likely the problems will occur. The following is a detailed discussion of the singleton design mode. In simple terms, the singleton mode ensures that only one class instance exists throughout the application. It is like an application in Java Web, which provides a global variable and is widely used, such as saving global data and implementing global operations. 1. The simplest implementation first, the simplest implementation that can be considered is to write the class constructor as private, so that other classes cannot be instantiated. Then return a static example in the class and return it to the caller. In this way, the caller can use this instance through this reference. Copy the public class Singleton {private static final Singleton singleton = new Singleton (); public static Singleton getInstance () {return singleton;} private Singleton () {}} to copy the code as shown in the preceding example, if an instance of SingletonClass needs to be used by an external user, it can only use the getInstance () method and its constructor is private. This ensures that only one object exists. 2. Performance Optimization-the code above lazy loaded is simple, but there is a problem-an instance object will be created no matter whether the class is used or not. If it takes a long time to create a database, such as connecting to the database for 10000 times (exaggerated ....), and this class may not be used, so this creation process is useless. What should I do? To solve this problem, we thought of a new solution: copy the code public class SingletonClass {private static SingletonClass instance = null; public static SingletonClass getInstance () {if (instance = null) {instance = new SingletonClass ();} return instance;} private SingletonClass () {}} there are two changes to the copied code-first, set the instance to null, determine whether the object is null when you use it for the first time to create an object. Because the object to be created is not declared, the final modifier must be removed. Let's imagine this process. To use SingletonClass, call the getInstance () method. When the instance is found to be null for the first time, an object is created and returned. When the instance is used again for the second time, because this instance is static and shares an object variable, the instance value is no longer null, so no object will be created and will be returned directly. This process is called lazy loaded, that is, loading late ----- It is loaded only when it is used. 3. Synchronize the above Code clearly and easily. However, as the famous saying goes: "80% of errors are caused by 20% of code optimization ". There is no problem with this code in A single thread, but if it is multi-threaded, the trouble will come. Let's analyze it: thread A wants to use SingletonClass and call the getInstance () method. Because it is the first call, A finds that the instance is null, so it starts to create an instance. At this time, the CPU has A time slice switch, thread B starts to execute, it needs to use SingletonClass, call the getInstance () method and check that the instance is null. Note that this is switched after detection by A. That is to say, A does not have time to create an object. Therefore, B starts to create the instance. After B is created, switch to A to continue execution. Because it has been detected, A will not detect it again, and it will directly create an object. In this way, thread A and thread B each have A SingletonClass object-singleton failure! The solution is also very simple, that is, lock: copy the code public class SingletonClass {private static SingletonClass instance = null; public synchronized static SingletonClass getInstance () {if (instance = null) {instance = new SingletonClass ();} return instance;} private SingletonClass () {}} copy the code as long as the synchronization lock is added to getInstance ,, A thread must wait until another thread is created before using this method. This ensures the uniqueness of the single benefit. 4. The code above performance is very clear and simple. However, it is often not ideal for simple things. This code undoubtedly has performance problems-the synchronization block modified by synchronized is several times slower than the normal code! If there are many getInstance () calls, you have to consider the performance issues ?!!! Let's analyze whether the entire method must be locked, or is it enough to lock a sentence tightly? Why should we lock it? Analyze the reason for lazy loaded's situation. The reason is that the null operation is detected and the object creation operation is separated, resulting in the uniqueness that only the synchronization lock can be used. If the two operations can be performed in an atomic manner, the single benefit is guaranteed. So we started to modify the code: copy the code public class SingletonClass {private static SingletonClass instance = null; public static SingletonClass getInstance () {synchronized (SingletonClass. class) {if (instance = null) {instance = new SingletonClass () ;}} return instance;} private SingletonClass () {}} copy the code first remove getInstance () and then load the synchronization lock to the if statement. However, such modifications do not play any role: because each call to getInstance () must be synchronized, performance problems still exist. If ...... we determine in advance whether it is null to synchronize? Copy the public class SingletonClass {private static SingletonClass instance = null; public static SingletonClass getInstance () {if (instance = null) {synchronized (SingletonClass. class) {if (instance = null) {instance = new SingletonClass () ;}} return instance;} private SingletonClass () {}} is there a problem copying the code? First, judge whether the instance is null. If it is null, the synchronization is performed. If it is not null, the instance object is directly returned. This is the single-profit pattern designed and implemented by double --- checked ---- locking. So far, everything is perfect. We use a clever way to implement the singleton mode. 5. Let's start with the compilation principle from the source check. The so-called compilation is to translate the source code into the target code-mostly the machine code. For Java, its target code is not the local machine code, but the virtual machine code. Compiler optimization is an important part in the compilation principle. The so-called Compiler optimization means that the program runs faster by adjusting the statement sequence without changing the original semantics. This process becomes reorder. You know, JVM is just a standard, not an implementation. The JVM does not specify Compiler Optimization content. That is to say, the JVM implementation can perform Compiler Optimization freely. Next, let's take a look at the steps required to create a variable? One is to apply for a piece of memory, call the constructor for initialization, and the other is to assign a pointer to this piece of memory. Who are behind these two operations? The JVM specification is not specified. In this case, JVM first develops a memory, points the pointer to the memory, and finally calls the constructor for initialization. Next we will consider this situation: thread A starts to create A SingletonClass instance. At this time, thread B calls the getInstance () method and first checks whether the instance is null. According to the memory model we mentioned above, A has directed the instance to the memory, but has not called the constructor. Therefore, B has detected that the instance is not null, so I directly returned the instance -- The problem occurred. Although the instance is not null, It is not constructed completely, just like a house has given you a key, but you cannot stay in it, because it is not cleaned up yet. At this point, if B uses this instance before A constructs the instance, the program will see an error! So we thought of the following code: copy the code public class SingletonClass {private static SingletonClass instance = null; public static SingletonClass getInstance () {if (instance = null) {SingletonClass SC; synchronized (SingletonClass. class) {SC = instance; if (SC = null) {synchronized (SingletonClass. class) {if (SC = null) {SC = new SingletonClass () ;}} instance = SC ;}} return instance ;} private SingletonCl Ass () {}} copies the code. We create a temporary variable in the first synchronization block and use this temporary variable to create an object, at last, the memory space of the temporary variables of the instance pointer is put. Writing this Code is based on the following idea: synchronized will block the code, and the code in the synchronization block is not associated with the external code. Therefore, operations on the Temporary Variable SC in the external synchronization block do not affect the instance, so the external class is in instance = SC; when the instance is detected before, the result instance is still null. However, this idea is totally wrong! The release of the synchronization block must be completed before -- that is, In the synchronization block -- but it is not guaranteed that the operations after the synchronization block cannot be switched to the end of the synchronization block due to compiler optimization. Therefore, the compiler can move the instance = SC; Statement to the internal synchronization block for execution. In this way, the program is wrong again! 6. If there are so many solutions, is there no way to implement it in Java for a Singleton? Not actually! After JDK 5, Java used a new memory model. Volatile keywords have clear semantics-before JDK1.5, volatile is a keyword, but it does not explicitly specify its purpose-write variables modified by volatile cannot be adjusted with the previous read/write code, the read variable cannot be adjusted with the subsequent read/write code! Therefore, we can simply add the volatile keyword to the instance. Copy the public class SingletonClass {private volatile static SingletonClass instance = null; public static SingletonClass getInstance () {if (instance = null) {synchronized (SingletonClass. class) {if (instance = null) {instance = new SingletonClass () ;}}return instance;} private SingletonClass () {}} copy the Code. However, this is only the Java solution after JDK1.5. What about the previous version? In fact, there is another solution that will not be affected by the Java version: copy the public class SingletonClass {private static class SingletonClassInstance {private static final SingletonClass instance = new SingletonClass ();} public static SingletonClass getInstance () {return SingletonClassInstance. instance;} private SingletonClass () {}} copies the Code. In this version of SingletonClass implementation code, we use the static internal class of Java. This technology is clearly stated by JVM, so there is no ambiguity. In this Code, because SingletonClass does not have a static attribute, It is not initialized. Until getInstance () is called, The SingletonClassInstance class will be loaded first. This class has a static SingletonClass instance. Therefore, you need to call the SingletonClass constructor and then getInstance () the instance of this internal class will be returned to the user. Because this instance is static, it will not be constructed multiple times. Because SingletonClassInstance is a private static internal class, it is not known to other classes. Similarly, static semantics requires that no instance exists. In addition, the JSL Specification defines that the class construction must be atomic and non-concurrent, so no synchronization block is required. Similarly, because the structure is concurrent, getInstance () does not need to be synchronized.