Summary of single-case mode and double detection

Source: Internet
Author: User

One of the classic patterns of design patterns--Singleton mode

This is also the interview often asked about the interview, generally require handwriting

"A Hungry man mode" non-delayed loading--space-time change

Lazy Mode delay load--change space in time

Seemingly simple, but in the lazy mode also hides a double detection, which is also related to the JVM memory "unordered write" problem (later use of volatile)


1. A Hungry man mode

Relatively simple, non-delayed loading, the object to new came out on the first

<span style= "Font-family:microsoft yahei;font-size:14px;"  >public class Singleton {private Singleton () {}//default constructor private static Singleton instance = new Singleton ();//Load public directly Singleton getintance () {return instance;}} </span>

2, lazy mode, delay loading"1" ordinary

<span style= "Font-family:microsoft yahei;font-size:14px;" >public class Singleton {private Singleton () {}//default constructor private static Singleton instance = null;//Delay load//each run creates an instance and thus A lock is required to protect public static synchronized Singleton getintance () {if (instance = = null) {instance = new Singleton ();//After judging load}retur n Instance;}} </span>



"2" double detection (defective from JVM itself)

Although this is done in a thread-safe way, and solves a multi-instance problem, it is not efficient. In any call to this method, you will have to bear the performance overhead of synchronization, but synchronization is only required at the time of the first call, that is, when a singleton class instance is created. This will prompt us to use the double check lock mode (double checked locking pattern), a method that locks only in the critical section code. It is generally called double check lock, because there will be two checks _instance = = NULL, one time without lock, and another on the synchronization block lock.

<span style= "Font-family:microsoft yahei;font-size:14px;" >public class Singleton {private Singleton () {}//default constructor private volatile static Singleton instance = null;//volatile Visibility/Prevent reordering public static Singleton getintance () {//First re-judgment if (instance = = NULL) {//Lock code block synchronized (singleton.class) {// Double-judge if (instance = = null) {instance = new Singleton ();//After judging load}}}return instance;}} </span>
If you use a double-check lock to implement a lazy singleton class, you need to increase the modifier volatile (visibility, prevent reordering) before the static member variable instance, and the volatile member variable ensures that multiple threads are handled correctly and that the code is only available in the JDK Correct execution in version 1.5 and above.

Single example of "3" threadlocal mode

<span style= "Font-family:microsoft yahei;font-size:14px;" > Public    class singleton{public        static final ThreadLocal  threadinstance=new ThreadLocal ();       public static Singleton Singleton=null;        public static Getsingleton () {           if (Threadinstance.get () ==null) {               Createsingleton ();            }        }        public static Singleton Createsingleton () {           synchronized (singleton.class) {             if (singleton==null) {                  Singleton=new Singleton ();   }}} </span>

Threadlocal global variable localization The first detection takes the thread part to do if the thread has already accessed it does not need to enter the synchronization block

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Summary of single-case mode and double detection

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.