Java design mode singleton mode (Singleton) [reprint]

Source: Internet
Author: User

Java design mode singleton mode (Singleton) [reprint]

Reprint Please specify source: http://cantellow.iteye.com/blog/838473

Objective

Lazy: create an object only when called

A hungry Man: object is created when class is initialized

The first type (lazy, thread insecure):

1  public classSingleton {2     Private StaticSingleton instance; 3     PrivateSingleton () {}4   5      public StaticSingleton getinstance () {6     if(instance = =NULL) {  7Instance =NewSingleton (); 8     }  9     returninstance; Ten     }   one}

This type of lazy loading is obvious, but the fatal is that the multithreading does not work properly.

The second type (lazy, thread safe):

1  public classSingleton {2     Private StaticSingleton instance; 3     PrivateSingleton () {}4      public Static synchronizedSingleton getinstance () {5     if(instance = =NULL) {  6Instance =NewSingleton (); 7     }  8     returninstance; 9     }  Ten}

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):

1  public classSingleton {2     Private StaticSingleton instance =NewSingleton (); 3     PrivateSingleton () {}4      public StaticSingleton getinstance () {5     returninstance; 6     }  7}

This approach avoids multi-threaded synchronization problems based on the Classloder mechanism, however, 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 obviously does not achieve the effect of lazy loading.

The fourth type ( hungry han, variant):

1  public classSingleton {2     Private StaticSingleton instance =NULL; 3     Static {  4Instance =NewSingleton (); 5     }  6     PrivateSingleton () {}7      public StaticSingleton getinstance () {8     returninstance; 9     }  Ten}

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):

1  public classSingleton {2     Private Static classSingletonholder {3     Private Static FinalSingleton INSTANCE =NewSingleton (); 4     }  5     PrivateSingleton () {}6      public Static FinalSingleton getinstance () {7     returnsingletonholder.instance; 8     }  9} 

This approach also takes advantage of the classloder mechanism to ensure that there is only one thread initialized 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 approach is reasonable compared to the third and fourth Approaches.

The sixth type (enumeration):

1  public enum Singleton {  2    INSTANCE;   3      public void whatevermethod () {  4    }  5 }   

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, 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):

1  public classSingleton {2     Private volatile StaticSingleton Singleton; 3     PrivateSingleton () {}4      public StaticSingleton Getsingleton () {5     if(singleton = =NULL) {  6         synchronized(Singleton.class) {  7         if(singleton = =NULL) {  8Singleton =NewSingleton (); 9         }  Ten         }   one     }   a     returnsingleton;  -     }   -}

This is the second way of the upgrade version, commonly known as double check lock, detailed information please see: http://www.ibm.com/developerworks/cn/java/j-dcl.html

After JDK1.5, the double-check lock is able to achieve a single-case effect normally.

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 first problem is fixed by overriding the GetClass method of the serialized class, specifying the same class of loaders

1 Private StaticClass getclass (String classname)2                                          throwsClassNotFoundException {3ClassLoader ClassLoader =thread.currentthread (). Getcontextclassloader (); 4       5       if(classLoader = =NULL)     6ClassLoader = Singleton.class. getClassLoader (); 7       8       return(classloader.loadclass (classname)); 9    }     Ten}

The second problem is fixed by writing the Readresolve method in the serialized class to return a singleton reference

1  public classSingletonImplementsjava.io.Serializable {2     public StaticSingleton INSTANCE =NewSingleton (); 3       4    protectedSingleton () {5         6    }7    8    //will be called in the ReadObject call stack of Objectinputstream.9    PrivateObject readresolve () {Ten             returnINSTANCE;  one       }     a}

For me, I prefer the third and fifth way, easy to understand, and in the JVM layer implemented Thread-safe (if not multiple ClassLoader environments), in general, I would use a third way, only in order to explicitly implement the lazy The fifth method is used when loading the effect , and I try to use enumerations to implement the singleton when it comes to deserializing the object, but I always make sure my program is thread-safe, and I never use the first and second ways, if there are other special needs, I might use the seventh way, after all, JDK1.5 has no double check lock problem Anymore.

========================================================================

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.

Java design mode singleton mode (Singleton) [reprint]

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.