Java design mode: Singleton mode; java Design Mode

Source: Internet
Author: User

Java design mode: Singleton mode; java Design 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. simplest implementation

First, the simplest implementation that can be thought of 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.

public class Singleton{    private static final Singleton singleton = new Singleton();        public static Singleton getInstance(){        return singleton;    }        private Singleton(){        }}

In the preceding example, if an external user needs to use a SingletonClass instance, only the getInstance () method can be used and its constructor is private. This ensures that only one object exists.

2. Performance Optimization-lazy loaded

The above code is simple, but there is a problem-no matter whether the class is used or not, an instance object will be created. 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 come up with a new solution:

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 Code-first, set the instance to null and determine whether to create an object when using the instance for the first time. 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. Synchronization

The above code is clear and simple. However, as the famous saying goes: "80% of errors are caused by 20% of code optimization ". There is no problem with this code under a single thread, but if it is multi-threaded, the trouble will come. Let's analyze it:

Thread A wants to use SingletonClass to 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, locking:

public class SingletonClass{    private static SingletonClass instance = null;    public synchronized static SingletonClass getInstance(){        if(instance == null){            instance = new SingletonClass();        }        return instance;    }    private SingletonClass(){        } }

As long as getInstance () is added with a synchronization lock, a thread must wait for the creation of another thread before using this method. This ensures the uniqueness of the single benefit.

4. Performance

The above code is very clear and simple. However, simple things are often not ideal. 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:

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(){        } }

First, remove the getInstance () operation and 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?

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 any problem? 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. check from source

Let's start with the compilation principles. 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:

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 SingletonClass() {   }     }
We create a temporary variable in the first synchronization block, then use this temporary variable to create the object, and finally put the memory space of the temporary variable of the instance pointer. 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 completely ErrorOf! 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. SolutionSo many examples can't be implemented in Java? 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.
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() {   }     }

However, this is only a 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:

public class SingletonClass {       private static class SingletonClassInstance {     private static final SingletonClass instance = new SingletonClass();   }   public static SingletonClass getInstance() {     return SingletonClassInstance.instance;   }   private SingletonClass() {   }     }
In the singleton implementation code of this version, 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. So far, we have fully understood the singleton mode in Java and proposed two solutions. I personally prefer the second method, and Effiective Java also recommends this method.
How does java Singleton mode (single design mode) ensure that only one instance can be generated? More specific explanation

I think this comment has been quite clear. The 23 Design Patterns of GOF are quite clear. For a Singleton, a Class has only one instance in a Classloader. If you write a private constructor in a class, you cannot create instances of this class except yourself. One static domain is your instance, NEW by myself, the static method that can be accessed by other classes only returns this instance, instead of New, so it is guaranteed that the second one cannot be created!

Q: What is the singleton Design Pattern in Java and what are the advantages?

Singleton mode: ensure that only one instance is available for one class. Advantage is its function. This class will always have only one instance.

Step: 1. Private the construction method of this class;
2. instantiate an instance of this class internally;

3. Provide interfaces for external access.

Public class SingletonDemo {
Private SingletonDemo () {}; // 1.

Private static SingletonDemo mInstance = new SingletonDemo (); // 2.

Public static SingletonDemo getInstance () {// 3.
Return mInstance;

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.