Java Singleton mode

Source: Internet
Author: User

The singleton (Singleton) pattern in Java is a widely used design pattern. The primary function of Singleton mode is to ensure that only one instance of a class exists in a Java program. Some managers and controllers are often designed as single-case patterns.

The singleton pattern has many advantages, it avoids the duplication of instance objects, not only reduces the time overhead of each object creation, but also saves memory space, and avoids the logic errors caused by manipulating multiple instances. If an object is likely to run through the entire application, and it acts as a global unified management control, then the singleton pattern may be a worthwhile choice.

There are many ways of writing a singleton pattern, most of which are more or less inadequate. The following will be described in each of these ways.

1. A Hungry man mode

[Java]View PlainCopy
    1. public class  singleton{  
    2.     private static singleton instance = new singleton ();   
    3.     private  singleton () {}  
    4.     public static singleton newinstance () {  
    5.          RETURN INSTANCE;  
    6.     }  
    7. }  

From the code we see that the constructor of the class is defined as private, that other classes cannot instantiate the class, and then provide a static instance and return it to the caller. The A Hungry man mode is the simplest implementation, and the A Hungry man mode creates the instance when the class loads, and the instance exists throughout the program cycle. The advantage of this is that only one instance is created at the time of class loading, there is no case that multiple threads create multiple instances, and the problem of multithreading synchronization is avoided. Its drawbacks are also obvious, even if the singleton is not used and will be created, and after the class is loaded, the memory is wasted.

This implementation is suitable for cases where a single case consumes less memory and is used at initialization time. However, if the single instance occupies a larger memory, or if the singleton is only used in a particular scenario, using the A Hungry man mode is inappropriate, then lazy loading is required.

2. Lazy mode

[Java]View PlainCopy
  1. Public class singleton{
  2. private static Singleton instance = null;
  3. Private Singleton () {}
  4. public static Singleton newinstance () {
  5. if (null = = instance) {
  6. Instance = new Singleton ();
  7. }
  8. return instance;
  9. }
  10. }

The singleton in lazy mode is created when it is needed, and if the singleton has been created, calling the Get interface again will not recreate the new object, but instead directly return the object created earlier. If a single instance uses fewer times and creates a single case that consumes more resources, you need to implement a singleton on-demand creation, which is a good choice when using lazy mode. But the lazy pattern here does not take into account the thread-safety issue, where multiple threads may call its getinstance () method concurrently, causing multiple instances to be created, and therefore requiring locking to resolve thread synchronization issues, as follows.

[Java]View PlainCopy
  1. Public class singleton{
  2. private static Singleton instance = null;
  3. Private Singleton () {}
  4. public static synchronized Singleton newinstance () {
  5. if (null = = instance) {
  6. Instance = new Singleton ();
  7. }
  8. return instance;
  9. }
  10. }

3. Double check Lock

The lock-in lazy mode seems to solve the problem of thread concurrency and delay loading, but it still has a performance problem and is not perfect. Synchronized modified synchronization method is much slower than the general method, if multiple calls to getinstance (), the cumulative performance loss is relatively large. So there is a double check lock, first look at its implementation code.

[Java]View PlainCopy
  1. Public class Singleton {
  2. private static Singleton instance = null;
  3. Private Singleton () {}
  4. public static Singleton getinstance () {
  5. if (instance = = null) {
  6. synchronized (Singleton. Class) {
  7. if (instance = = null) {//2
  8. Instance = new Singleton ();
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. }

You can see that above the synchronization code block more than a layer of instance empty judgment. Because the singleton object needs to be created only once, if you call getinstance () again later, you only need to return the singleton directly. Therefore, in most cases, calling getinstance () does not execute to the synchronous code block, which improves program performance. However, it is also necessary to consider a situation, if two threads A, B,a executes the if (instance = = NULL) statement, it will assume that the singleton object is not created, this time the line Cheng Che to B also executed the same statement, B also considered that the Singleton object was not created, and then two threads sequentially execute the synchronization code block, And a singleton object is created separately. To solve this problem, you also need to add the if (instance = = NULL) statement in the synchronization code block, which is the code 2 seen above.

We see the double-check lock is the implementation of the delay load, but also solve the problem of thread concurrency, as well as solve the efficiency of the implementation of the problem, is it really foolproof?

Here we refer to the instruction rearrangement optimizations in Java. The so-called order rearrangement optimization means that the program runs faster by adjusting the order of execution without altering the original semantics. The JVM does not dictate the compiler to optimize the content, which means that the JVM is free to optimize the order reordering.

The key to this problem is that the order of initialization singleton and assigning object addresses to instance fields is indeterminate because of the presence of command rearrangement optimizations. When a thread creates a singleton object, it allocates memory space for the object and sets the object's field to the default value before the constructor method is called. The allocated memory address can now be assigned to the instance field, but the object may not have been initialized yet. If the next thread is called getinstance, and the object is not in the correct state, the program will go wrong.

This is the reason for the double-check lock to fail, but fortunately added the volatile keyword in JDK1.5 and later versions. One of the semantics of volatile is the prohibition of command reordering optimizations, which ensures that the object is already initialized when the instance variable is assigned, thus avoiding the problem mentioned above. The code is as follows:

[Java]View PlainCopy
  1. Public class Singleton {
  2. private Static volatile Singleton instance = null;
  3. Private Singleton () {}
  4. public static Singleton getinstance () {
  5. if (instance = = null) {
  6. synchronized (Singleton. Class) {
  7. if (instance = = null) {
  8. Instance = new Singleton ();
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. }

4. Static internal class

In addition to the above three ways, there is another way to implement the Singleton, through the static inner class to achieve. First, take a look at its implementation code:

[Java]View PlainCopy
  1. Public class singleton{
  2. private static class singletonholder{
  3. public static Singleton instance = new Singleton ();
  4. }
  5. Private Singleton () {}
  6. public static Singleton newinstance () {
  7. return singletonholder.instance;
  8. }
  9. }

This approach also leverages the class loading mechanism to ensure that only one instance instance is created. It is the same as the A Hungry man mode, it also takes advantage of the class loading mechanism, so there is no problem of multithreading concurrency. Not the same, it is inside the inner class to create an object instance. In this case, as long as the application does not use an inner class, the JVM does not load the singleton class, nor does it create a singleton object, thus allowing lazy lazy loading. In other words, this approach can guarantee both lazy loading and thread safety.

5. Enumeration

Let's look at the last way to implement this article: enumerations.

[Java]View PlainCopy
    1. Public enum singleton{
    2. Instance
    3. public void Whatevermethod () {}
    4. }

There are common drawbacks to the four ways in which you can implement a single example:

1) Additional work is required for serialization, or a new instance is created each time a serialized object is deserialized.

2) You can use reflection to forcibly invoke the private constructor (if you want to avoid this, you can modify the constructor so that it throws an exception when creating the second instance).

While the enumeration class solves both of these problems, the use of enumerations in addition to thread-safe and anti-reflection call constructors also provides an automatic serialization mechanism that prevents the creation of new objects when deserializing. Therefore, the effective Java authors recommend the method used. In practice, however, it is rare to see someone write like that.

Summarize

This article summarizes five kinds of Java implementation of the single-case approach, of which the first two are not perfect, double-check lock and static internal classes can solve most problems, usually the most used in the work is also the two ways. Although the enumeration is a perfect solution to a variety of problems, but this kind of writing is somewhat unfamiliar. Personal advice is to use a third and fourth way to implement a singleton pattern without special needs.

Reproduced in: http://blog.csdn.net/goodlixueyong/article/details/51935526

Java Singleton mode

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.