Java Singleton mode

Source: Internet
Author: User
Tags volatile

The singleton mode may be the least code mode, but less does not necessarily mean simple, want to use good, with the singleton mode, it really cost a brain. This paper makes a summary of the common pattern in java, if there are errors or omissions, please correct the reader.

A hungry man method

As the name implies, the A Hungry man method creates an object instance when the class is first referenced, regardless of whether it is actually required to be created. The code is as Follows:

 public class Singleton {      privatestaticnew  Singleton ();     Private Singleton () {}      public Static Getsignleton () {        return  singleton;    }}

The benefit of this is that writing is simple, but it is not possible to delay the creation of Objects. But most of the time we want the object to delay loading as much as possible to reduce the load, so we need the following lazy method:

Single thread notation

This notation is the simplest, consisting of a private constructor and a public static factory method, which singleton null in the factory method, and if NULL is the new one, and finally returns the singleton Object. This approach allows for delayed loading, but there is a fatal weakness: thread Insecurity. If you have two threads that call the Getsingleton () method at the same time, there is a great chance that the object will be created Repeatedly.

 public class Singleton {    privatestaticnull;     Private Singleton () {}      public Static Singleton Getsingleton () {        ifnullnew  Singleton ();         return singleton;}    }

Consider Thread-safe notation

This notation takes into account thread safety and locks the null judgment on Singleton and the new part using Synchronized. At the same time, the singleton object is restricted by using the volatile keyword, guaranteeing its visibility to all threads, and prohibiting command reordering Optimizations. It is thus possible to semantically guarantee that this singleton pattern is thread-safe. Note that this is said to be semantically, the actual use of the existence of small pits, will be written in the following Text.

 public classSingleton {Private Static volatileSingleton Singleton =NULL; PrivateSingleton () {} public StaticSingleton Getsingleton () {synchronized(Singleton.class){            if(singleton = =NULL) {singleton=NewSingleton (); }        }        returnsingleton; }    }

Take into account the thread safety and efficiency of the wording

Although the above-mentioned notation can be run correctly, it is inefficient and cannot be applied in Practice. Because every time you call the Getsingleton () method, you have to queue up here at synchronized, and it is very rare to actually encounter a new Situation. therefore, A third form of writing is born:

 public classSingleton {Private Static volatileSingleton Singleton =NULL; PrivateSingleton () {} public StaticSingleton Getsingleton () {if(singleton = =NULL){            synchronized(Singleton.class){                if(singleton = =NULL) {singleton=NewSingleton (); }            }        }        returnsingleton; }    }

This notation is called a "double-check lock", as the name implies, in the Getsingleton () method, two times the null Check. Seemingly superfluous, but actually dramatically increases concurrency, which in turn improves performance. Why is it possible to increase the degree of concurrency? As mentioned above, the case of new in the Singleton is very small, and the vast majority of them are read operations that can be parallel. therefore, more than one null check before locking can reduce the vast majority of lock operation, the efficiency of the implementation of the goal is Achieved.

Keng

So is this a perfectly safe formulation? As I said earlier, there is no problem from a semantic point of view. But there is still a pit. Before we say this hole, we have to look at the volatile Keyword. In fact, this keyword has two layers of semantics. The first layer of semantics is believed to be more familiar and visible to All. Visibility refers to the modification of the variable in a thread that is immediately written back to the main memory by the work memory, so it is immediately reflected in the read operation of the other THREAD. By the way, working memory and main memory can be approximately understood as the actual computer cache and primary storage, the working memory is the thread exclusive, main memory is Thread-shared. The second layer of volatile semantics is the prohibition of command reordering Optimizations. We know that the code we write (especially multithreaded code), because of compiler optimizations, may actually be executed in a different order than we Write. The compiler only guarantees that the program executes the same results as the source code, but does not guarantee that the order of the actual instructions is the same as the source Code. This looks fine on a single thread, but once multiple threads are introduced, this disorder can cause serious problems. The volatile keyword can be used to solve this problem semantically.

Note that "there is no semantic problem" mentioned repeatedly, but unfortunately, it is not possible to disable the instruction rearrangement optimization until jdk1.5 will work correctly. Even declaring variables as volatile in the previous JDK did not completely avoid the problem caused by reordering. therefore, in the jdk1.5 version, the double check lock form of the singleton mode is not guaranteed to be thread-safe.

A hungry man type static final field

This approach is very simple because instances of Singleton are declared as static and final variables, initialized when the class is first loaded into memory, so creating the instance itself is thread Safe.

 public  class   singleton{ //  Initializes the  private  static  
   
    final  Singleton instance = 
     Singleton     ();  
    private  
     Singleton () {}  
    public  
    static  
     Singleton getinstance () {     
    return  
     instance; }}
   

This kind of writing, if perfect, there is no need to nag so many double lock problem. The disadvantage is that it is not a lazy load mode (lazy initialization), and a single session is initialized at the beginning of the load class, even if the client does not call the getinstance () method. The creation of a hungry man is not available in some scenarios: for example, if the creation of a Singleton instance is dependent on a parameter or configuration file, a method must be called before getinstance () to set the parameter to it, so that the singleton can not be used.

Static internal class method

so, is there a time-lapse load and a simple way to keep thread safe? We can put the singleton instance into a static inner class, which avoids the creation of the static instance when the Singleton class is loaded, and because the static inner class is only loaded once, this is also thread-safe:

 public class Singleton {    privatestaticclass  Holder {        Private Static New Singleton ();    }         Private Singleton () {}              public Static Singleton Getsingleton () {        return  holder.singleton;    }}

however, There are two common drawbacks to all of the implementations mentioned above:

    • Requires additional work (Serializable, transient, readresolve ()) to serialize, or a new instance is created each time a serialized object instance is Deserialized.
    • You might be forced to call our private constructor with reflection (if you want to avoid this, you can modify the constructor so that it throws an exception when creating the second instance).
Enumeration notation

Of course, There is a more elegant way to implement the Singleton pattern, which is the enumeration notation:

 public enum Singleton {    INSTANCE;     Private String name;      public String getName () {        return  name;    }      public void setName (String name) {        this. name = name;    }} 

The use of enumerations, in addition to Thread-safe and Anti-Reflection forced invocation of the constructor, also provides an automatic serialization mechanism to prevent deserialization when a new object is Created. therefore, effective Java recommends using enumerations as much as possible to implement the Singleton.

Summarize

This article sent out after a lot of feedback, it makes me feel flattered, think should write a little summary. The code is not written once and for all, only in the most appropriate wording under certain conditions. Under different platforms and different development environments (especially JDK versions), There are different optimal solutions (or better solutions).
For example, enumeration, Although effective Java is recommended, but on the Android platform is not Recommended. Clearly stated in this Android training:

Enums often require more than twice as much memory as static Constants. You should strictly avoid using enums on ANDROID.

again, such as double-check lock method, can not be used before jdk1.5, and on the Android platform is more comfortable to use (generally Android is more than jdk1.6, not only fixed the volatile semantic problem, but also added a lot of lock optimization, so that the cost of multi-threaded synchronization to reduce a lot).

finally, regardless of the approach, keep in mind the three main points of the single case:

    • Thread Safety
    • Lazy Loading
    • Serialization and deserialization security

Transferred from: http://www.tekbroaden.com/singleton-java.html

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.