Singleton mode-Creation Mode

Source: Internet
Author: User

Reprinted: http://cantellow.iteye.com/blog/838473

 

 

Java code
  1. Public class Singleton {
  2. Private Static Singleton instance;
  3. Private Singleton (){}
  4. Public static Singleton getinstance (){
  5. If (instance = NULL ){
  6. Instance = new Singleton ();
  7. }
  8. Return instance;
  9. }
  10. }

 

This lazy loading method is obvious, but it is fatal that it cannot work normally in multiple threads.

 

Second (lazy, thread security ):

 

Java code
  1. Public class Singleton {
  2. Private Static Singleton instance;
  3. Private Singleton (){}
  4. Public static synchronized Singleton getinstance (){
  5. If (instance = NULL ){
  6. Instance = new Singleton ();
  7. }
  8. Return instance;
  9. }
  10. }

 

This method can work well in multiple threads, and it seems that it also has a good lazy loading. However, unfortunately, the efficiency is very low. In 99% cases, synchronization is not required.

 

Third (Ele. Me ):

 

Java code
  1. Public class Singleton {
  2. Private Static Singleton instance = new Singleton ();
  3. Private Singleton (){}
  4. Public static Singleton getinstance (){
  5. Return instance;
  6. }
  7. }

 

This method is based on the classloder mechanism to avoid multi-thread synchronization. However, instances are instantiated during class loading. Although there are many causes for class loading, in Singleton mode, most of them call the getinstance method, but it cannot be determined that other methods (or other static methods) cause class loading, at this time, the initialization of the Instance obviously does not achieve the lazy loading effect.

 

Fourth (Ele. MeChinese, variant ):

 

Java code
  1. Public class Singleton {
  2. Private Singleton instance = NULL;
  3. Static {
  4. Instance = new Singleton ();
  5. }
  6. Private Singleton (){}
  7. Public static Singleton getinstance (){
  8. Return this. instance;
  9. }
  10. }

 

On the surface, it seems that the difference is quite big. In fact, the third method is almost the same. They are all instantiated in class initialization.

 

Fifth (static internal class ):

 

Java code
  1. Public class Singleton {
  2. Private Static class singletonholder {
  3. Private Static final Singleton instance = new Singleton ();
  4. }
  5. Private Singleton (){}
  6. Public static final Singleton getinstance (){
  7. Return singletonholder. instance;
  8. }
  9. }

 

This method also uses the classloder mechanism to ensure that there is only one thread during instance initialization. It is different from the third and fourth methods (very slightly different ): the third and fourth ways are as long as the singleton class is loaded, the instance will be instantiated (not achieving the lazy loading effect), and this method is because the singleton class is loaded, the instance is not necessarily initialized. Because the singletonholder class is not actively used, the singletonholder class is displayed and instantiated only when the getinstance method is called. Imagine that instantiating an instance consumes a lot of resources and I want to delay loading. On the other hand, I don't want to instantiate it when the singleton class is loaded, because I cannot ensure that the singleton class may be actively used and loaded elsewhere, it is obviously inappropriate to instantiate the instance at this time. At this time, this method is more reasonable than the third and fourth methods.

 

Type 6 (enumeration ):

 

Java code
  1. Public Enum Singleton {
  2. Instance;
  3. Public void whatevermethod (){
  4. }
  5. }

 

This method is advocated by Josh Bloch, author of objective java. It not only avoids multithread synchronization, but also prevents deserialization and re-creation of new objects, which is a strong barrier, however, I personally think that because Enum is added only in 1.5, it is difficult to write in this way. In actual work, I rarely see anyone writing this.

 

Article 7 (dual verification lock ):

 

Java code
  1. Public class Singleton {
  2. Private volatile static Singleton;
  3. Private Singleton (){}
  4. Public static Singleton getsingleton (){
  5. If (Singleton = NULL ){
  6. Synchronized (singleton. Class ){
  7. If (Singleton = NULL ){
  8. Singleton = new Singleton ();
  9. }
  10. }
  11. }
  12. Return Singleton;
  13. }
  14. }

 

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

After jdk1.5, the dual-check lock can achieve normal Singleton effect.

 

Summary

Note the following two issues:

1. If a singleton is loaded by different classloaders, there may be multiple Singleton instances. It is assumed that it is not a remote access. For example, some servlet containers use different class loaders for each servlet. In this way, if two servlets access a singleton class, they will all have their own instances.

2. If Singleton implements the java. Io. serializable interface, the instances of this class may be serialized and restored. In any case, if you serialize an object of the singleton class and restore multiple objects, you will have instances of multiple Singleton classes.

The solution to the first problem is:

 

Java code
  1. Private Static class getclass (string classname)
  2. Throws classnotfoundexception {
  3. Classloader = thread. currentthread (). getcontextclassloader ();
  4. If (classloader = NULL)
  5. Classloader = singleton. Class. getclassloader ();
  6. Return (classloader. loadclass (classname ));
  7. }
  8. }

The solution to the second problem is:

 

Java code
  1. Public class Singleton implements java. Io. serializable {
  2. Public static Singleton instance = new Singleton ();
  3. Protected Singleton (){
  4. }
  5. Private object readresolve (){
  6. Return instance;
  7. }
  8. }

 

For me, I prefer the third and fifth methods, which are easy to understand and implement thread security at the JVM layer (if not multiple class loaders ), in general, I will use the third method. The fifth method is used only when the lazy loading effect is explicitly implemented. In addition, if deserialization is involved in object creation, I will try to use enumeration to implement singleton. However, I will always ensure that my program is thread-safe, in addition, I will never use the first and second methods. If there are other special requirements, I may use the seventh method. After all, jdk1.5 has no problem of double check locking.

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

Superheizai summarized the following points:

 

However, in general, the first type is not a Singleton, and the fourth and third types are the same. If so, the fifth type can be written separately. Therefore, the Singleton is generally written in five ways. Lazy, cool, dual verification lock, enumeration and static internal class.

I am very glad to have such a reader.

 

Singleton mode-Creation 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.