Seven ways to understand the new (Java implementation) Singleton pattern

Source: Internet
Author: User

The first type (lazy, thread insecure): Java code public class Singleton {private static Singleton instance;  Private Singleton () {} public static Singleton getinstance () {if (instance = = null) {instance = new      Singleton ();      } return instance; }} This type of lazy loading is obvious, but the fatal is that multithreading does not work correctly.      The second type (lazy, thread safe): Java code public class Singleton {private static Singleton instance; Private Singleton () {} public static synchronized Singleton getinstance () {if (instance = null) {INS      tance = new Singleton ();      } return instance; }} This can work well in multiple threads, and it looks like it also has a good lazy loading, but, unfortunately, is inefficient and does not require synchronization in 99% cases.      The third type (a hungry man): Java code public class Singleton {private static Singleton instance = new Singleton ();      Private Singleton () {} public static Singleton getinstance () {return instance; }} This approach avoids multi-threaded synchronization problems based on the classloder mechanism, but instance is instantiated at class loading, although there are many reasons for class loading, most of which are called getinstance methods in singleton mode. However, it is not certain that there are other ways (or other static methods) that cause the class to load, when initializing instance is obviously notAchieve the effect of lazy loading.      Fourth type (a Hungry Man, variant): Java code 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. Fifth type (Static inner Class): Java code public class Singleton {private static class Singletonholder {private static final Singleto      n INSTANCE = new Singleton ();      } private Singleton () {} public static final Singleton getinstance () {return singletonholder.instance; This approach also leverages the Classloder mechanism to ensure that only one thread is initialized with instance, which 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 is a way of looking at the third and fourth waysReasonable.      Sixth type (enum): Java code public enum Singleton {INSTANCE; public void Whatevermethod () {}} This approach is advocated by effective Java author Josh Bloch, which not only avoids multithreading synchronization problems, but also prevents deserialization from recreating new objects, which can be a very strong wall Ah, but, personally, because of the 1.5 to join the enum feature, in this way to write can not help people feel unfamiliar, in the actual work, I also rarely see someone write so.      Seventh type (double check lock): Java code 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; }} This is the second way of upgrading, commonly known as double check Lock, detailed information please see: http://www.ibm.com/developerworks/cn/java/j-dcl.html after JDK1.5, double check lock can achieve the single case effect normally. Summary 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 first problem is fixed: Java code private static Class getclass (String classname) throws ClassNotFoundException {                 ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader ();                 if (ClassLoader = = null) ClassLoader = Singleton.class.getClassLoader ();        Return (Classloader.loadclass (classname)); }} to fix the second problem is: Java code public class Singleton implements java.io.Serializable {public static Singleton INS              tance = new Singleton ();           Protected Singleton () {} private Object Readresolve () {return INSTANCE; }} for me, I prefer the third and fifth way, easy to understand, and in the JVM layer to implement thread safety (if not multiple classloader environment), in general, I will use the third way, only when you want to explicitly implement the lazy loading effect will use 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. ======================================================================== Superheizai classmate summed up very in place: But generally speaking, the first kind does not count as a single case, A fourth and a third is a kind of, ifIf you count, the fifth type 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 understand the new (Java implementation) Singleton pattern

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.