Singleton mode four thread-safe implementations

Source: Internet
Author: User

1. Description:

Singleton (singleton) is a design pattern, in order to ensure that a class has only one instance, and provides a global access point to access it.

2. Main features:

1) The Singleton class ensures that it has only one instance ( constructor private: not externally instantiated or inherited ).

2) A singleton class must create its own instance.

3) The Singleton class must provide a unique instance for other objects.

3. Application of the singleton mode:

Resource Manager , Recycle Bin, printer resource, thread pool, cache, configuration information class, management class, control class, façade class, proxy class is usually designed as a singleton class

If the program has more than one class loader and uses the singleton mode at the same time, it is possible that multiple singleton coexistence will find a corresponding solution.

4. Implementation method:

If an application always creates and uses a singleton instance, or when it is created and run, the overhead is small.


1). Eager initialization a hungry man Singleton class (dependent JVM creates a unique singleton instance when loading a class)

The public class Eagersingleton {          //JVM guarantees that the instance must have been created before any thread accesses the uniqueinstance static variables,          private static Eagersingleton Uniqueinstance = new Eagersingleton ();            Private default constructor to ensure that the outside world cannot instantiate          private Eagersingleton () {          }            //provide global access point to get unique instance public          static Eagersingleton GetInstance () {                  return uniqueinstance;          }  }
IfThe overhead is large, you want to use the time only to consider deferred instantiation, or singleton initialization requires some external resources (such as network or storage devices), it is necessary to use the latter method.

2) lazy initialization  lazy Singleton class

public class Lazysingleton {          private static Lazysingleton uniqueinstance;            Private Lazysingleton () {          } public            static synchronized Lazysingleton getinstance () {                  if (uniqueinstance = = NULL)                          uniqueinstance = new Lazysingleton ();                  return uniqueinstance;          }  
synchronizing a method can result in a 100 times-fold reduction in program execution, and there is absolutely no need to lock each call to getinstance. in fact, we just want to make sure that the initial success, the rest of the fast return, if the getinstance frequently used in places to consider the re-optimization.

3) "Double check Lock" (double-checked Lock) as far as possible "lock" delay, only when needed "lock" (only for Java version 5.0, volatile guaranteed atomic operation)
Happens-before: "What what must be run before what is," is to guarantee the order.
Now the CPU has the ability to execute in a disorderly order (that is, the instruction will be disorderly or run in parallel, can not be executed in the order of the code we write the memory of the access process), and the cache between multiple CPUs is not guaranteed to synchronize in real time, only the above happens-before to ensure the order of the case.

The JVM is able to properly reorder machine instructions based on the characteristics of the CPU (multi-level cache system, multi-core processor, etc.), so that the machine instructions are more consistent with the performance of the CPU and the machine is maximized.

If there is no volatile modifier then there may be a thread T1 B operation and another T2 C operation between the instance read and write without happens-before, may cause the phenomenon is T1 B operation has not been fully constructed successfully, But T2 C has seen instance as non-empty, so that T2 directly returns the instance references that are not fully constructed, and T2 will have problems with instance to do something about it.

volatile features:
1. Avoid the compiler to cache variables in registers
2. Prevent the compiler from adjusting the order of code execution

The optimizer must carefully reread the value of this variable each time it is used, rather than using a backup stored in the register.

public class Doublecheckedlockingsingleton {///Java uses double check locking mechanism due to the reason of Java compiler and JIT optimization          The system cannot guarantee the order of execution we expect. When java5.0 modifies the memory model, variables declared with volatile can force the mask compiler and JIT optimizations to work private volatile static Doublecheckedlockingsingleton unique            Instance; Private Doublecheckedlockingsingleton () {} public static Doublecheckedlockingsingleton getinstance () {if (uniqueinstance = = null) {synchronized (Doublecheckedlockingsingleton.clas s) {if (uniqueinstance = = null) {Uniqueinstanc                                  E = new Doublecheckedlockingsingleton ();          }}} return uniqueinstance; }  }  
4) The Lazy initialization holder class satisfies all double-checked Locking conditions and does not show the synchronization action
public class Lazyinitholdersingleton {          private Lazyinitholdersingleton () {          }            private Static class Singletonholder {                  private static final Lazyinitholdersingleton INSTANCE = new Lazyinitholdersingleton ();          }            public static Lazyinitholdersingleton getinstance () {                  return singletonholder.instance;          }  }  
according to the JVM specification, when an object calls Lazyinitholdersingleton.getinstance () for the first time, the Lazyinitholdersingleton class is first actively used. The JVM initializes it (the Lazyinitholdersingleton () constructor is not called at this time), and then Lazyinitholdersingleton calls the GetInstance () method, which The first active use of the Singletonholder class, so to initialize the Singletonholder class, initialization, the instance constant is assigned to call the The Lazyinitholdersingleton constructor method, Lazyinitholdersingleton (), completes the instantiation and returns the instance. when another object (perhaps in another thread) calls Lazyinitholdersingleton.getinstance () again, because it has already been initialized, no more initialization steps are taken. So the direct return instance constant is the same Lazyinitholdersingleton instance.

Singleton mode four thread-safe implementations

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.