Several implementations of the single-instance mode of thread safety

Source: Internet
Author: User
Tags volatile

The singleton pattern is a common design pattern, and the Java Singleton pattern provides us with the possibility of such implementations. The advantage of using singleton is that you can save memory because it limits the number of instances,

facilitates Java garbage collection (garbage collection).


The singleton mode is also a kind of common design pattern, what does it bring to our advantage? In fact, it is nothing more than a three-part function:

1, control the use of resources, through thread synchronization to control the concurrent access of resources;

2, control the number of instances produced, to achieve the purpose of saving resources.

3, as the use of communications media, that is, data sharing, it can not establish a direct association under the conditions of a number of unrelated two threads or processes to achieve communication between.


The singleton pattern is divided into three kinds: lazy type single case, a hungry man type single case, registration type single case three kinds.

There are a few features of the Singleton model:

1, the Singleton class can have only one instance.

2, the Singleton class must create its own unique instance.

3. The Singleton class must provide this instance to all other objects.


There are several ways to implement a thread-safe singleton pattern, and the 2nd option is considered the most elegant by individuals:
1. A Hungry man type
2, the use of internal class
3, Ordinary lock solution
4, double detection, but pay attention to the wording
If the monomer mode continues to expand to n-ary monomer mode, it is the object pool mode.

1. [code] a hungry man type single case
When the class is loaded, the unique instance has been created
 Public class Singleton {   privatestaticnew  Singleton ();    Private Singleton () {}     Public Static Singleton getinstance () {      return  INSTANCE;   }}

2. [code] with an internal class
 public  class   Singleton {  Singleton () {}  private  static  Span style= "color: #0000ff;" >class   Singletonholder { private  Final static  Singleton INSTANCE = new  Span style= "color: #000000;"   > Singleton ();  public  static   Singleton getinstance () { return     Singletonholder.instance; }}
is a lazy singleton, because the Java mechanism stipulates that the inner class Singletonholder is loaded (and lazy) only when the getinstance () method is first called, and its loading process is thread-safe. An instance is instantiated once when the inner class is loaded.
3. [Code] General lock resolution
 Public class Singleton {   privatestaticnull;    Private Singleton () {}
   publicstatic  synchronized Singleton getinstance () {
if NULL          {new  Singleton ();      }       return instance;}   }

The static factory method, which returns only instances of this class, is initialized when the instance is found not initialized.
Although thread safety is resolved, but each thread calls getinstance to lock, we want to lock only when the first call to GetInstance, see the following double detection scheme

4. [code] dual detection scheme
 Public classSingleton {Private StaticSingleton instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {if(Instance = =NULL) {synchronzied (Singleton.class) {Singleton temp=instance; if(temp = =NULL) {Temp=NewSingleton (); Instance=Temp}} }      returninstance; }}
Because of the order reordering problem, it is not possible to write directly as follows:
 Public classSingleton {Private StaticSingleton instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {if(Instance = =NULL) {synchronzied (Singleton.class) {            if(Instance = =NULL) {instance=NewSingleton (); }         }      }      returninstance; }}
However, if the instance instance variable is modified with a volatile modifier, the volatile modifier will ensure that instance = new Singleton (), the corresponding instruction is not reordered, and the following code is thread-safe:
 Public classSingleton {Private Static volatileSingleton instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {if(Instance = =NULL) {synchronzied (Singleton.class) {            if(Instance = =NULL) {instance=NewSingleton (); }         }      }      returninstance; }}

Several implementations of the single-instance mode of thread safety

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.