Seven ways to style Java Singleton

Source: Internet
Author: User
Tags serialization static class

The first type (lazy, thread insecure):
public class Singleton {      private static Singleton instance;      private Singleton (){}      public static Singleton getInstance() {      if (instance == null) {          instance = new Singleton();      }      return instance;      }  }  
The second type (lazy, thread safe):
public class Singleton {      private static Singleton instance;      private Singleton (){}      public static synchronized Singleton getInstance() {      if (instance == null) {          instance = new Singleton();      }      return instance;      }  }  

This notation works well in multi-threading, and it seems to have a good lazy loading, but, unfortunately, is inefficient and does not require synchronization in 99% cases.

The third type (a Hungry man):
public class Singleton {      private static Singleton instance = new Singleton();      private Singleton (){}      public static Singleton getInstance() {      return instance;      }  }  

This approach is based on classloder mechanisms, in-depth analysis of Java's classloader mechanism (source level) and Java class loading, linking and initialization of two articles on the classload mechanism of the thread safety issues, to avoid the synchronization of multi-threaded problems, however, instance When class loading is instantiated, although there are many reasons for class loading, most of them are called methods in Singleton mode, but there is no getInstance way to determine if there are other ways (or other static methods) that cause the class to load, at which point instance the initialization obviously does not achieve lazy loading the effect.

Fourth species (a Hungry man, variant):
public class Singleton {      private Singleton instance = null;      static {      instance = new Singleton();      }      private Singleton (){}      public static Singleton getInstance() {      return this.instance;      }  }  

The surface looks very different, in fact, the third Way is similar, all in class initialization is instantiated instance.

The fifth type (static inner Class):
public class Singleton {      private static class SingletonHolder {      private static final Singleton INSTANCE = new Singleton();      }      private Singleton (){}      public static final Singleton getInstance() {      return SingletonHolder.INSTANCE;      }  }  

This approach also leverages classloder the mechanism to ensure that instance only one thread is initialized, and it differs from the third and fourth ways (very subtle differences): The third and fourth ways are as long as the Singleton class is loaded, Then instance will be instantiated (without the lazy loading effect), and this is singleton class is loaded, instance not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only if it is displayed by calling the GetInstance method, thus instantiating the instance. Imagine if instantiating instance is draining resources, I want him to delay loading, on the other hand, I don't want to instantiate when the singleton class loads, because I can't make sure that the Singleton class can be actively used in other places to be loaded, It is obviously inappropriate to instantiate instance at this time. At this point, this approach is reasonable compared to the third and fourth approaches.

The sixth type (enumeration):
public enum Singleton {      INSTANCE;      public void whateverMethod() {      }  }  

This approach is advocated by effective Java author Josh Bloch, which not only avoids multi-threaded synchronization problems, but also prevents deserialization from recreating new objects, which can be a very strong barrier. The thread safety and serialization issues for enumerations are described in detail in the thread safety and serialization issues of enumeration types----enumerations in the depth analysis of Java, but Personally think that because of the 1.5 to join the enum characteristics, in this way to write inevitably people feel unfamiliar, in the actual work, I also rarely see someone write so.

Seventh type (double check lock):
public class Singleton {      private volatile static Singleton singleton;      private Singleton (){}      public static Singleton getSingleton() {      if (singleton == null) {          synchronized (Singleton.class) {          if (singleton == null) {              singleton = new Singleton();          }          }      }      return singleton;      }  }  
Summarize

There are two issues to note:

1. If a singleton is loaded by a different class loader, there may be instances of multiple singleton classes. It is assumed that not remote access, such as some servlet containers, use a completely different class loader for each servlet, so that if there are two Servlets accessing a singleton class, they will have their own instance.

2. If the singleton implements the Java.io.Serializable interface, then instances of this class may be serialized and restored. In any case, if you serialize an object of a singleton class and then restore multiple objects, you will have multiple instances of the Singleton class.

The fix to the first problem is: private static Class getclass (String classname)
Throws ClassNotFoundException {
ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader ();

      if(classLoader == null)              classLoader = Singleton.class.getClassLoader();           return (classLoader.loadClass(classname));        }     }  

The fix for the second problem is:

public class Singleton implements java.io.Serializable {        public static Singleton INSTANCE = new Singleton();        protected Singleton() {        }        private Object readResolve() {                 return INSTANCE;      

For me, I prefer the third and fifth way, easy to understand, and thread-safe in the JVM layer (if not multiple classloader environments), in general, I will use the third way, only if you want to explicitly implement the lazy loading effect will be used in the fifth way, in addition, If it involves deserializing the creation of an object I will try to implement the singleton using enumerations, but I will always ensure that my program is thread safe, and I will never use the first and second way, if there are other special needs, I may use the seventh way, after all, JDK1.5 has no problem with double-check locking.

However, in general, the first is not a single case, the fourth and the third is a kind, if counted, the fifth can also be written separately. Therefore, the general single case is five kinds of writing. Lazy, bad Han, double check lock, enumeration and static inner class.

Seven ways to style Java Singleton

Related Article

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.