Java design pattern-Singleton mode

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/jason0539/article/details/23297037

In Java, the singleton pattern is a common design pattern, the single-case pattern has a variety of ways, here are mainly only: lazy type single case, a hungry man type single case

  Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole

Select singleton mode to avoid inconsistent state and reduce resource consumption

One, lazy type single case
1 //Lazy Type Singleton class. Instantiate yourself at the first call2  Public classSingleton {3     PrivateSingleton () {}4     Private StaticSingleton single=NULL; 5     //Static Factory Method6      Public StaticSingleton getinstance () {7          if(single =NULL) {    8Single =NewSingleton (); 9          }    Ten         returnSingle ;  One     }   A}

Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope.

However, the above-mentioned lazy singleton implementation does not take into account the thread safety problem, it is thread insecure, the concurrency environment is likely to have multiple singleton instances, to achieve thread safety, there are the following three ways, is to getinstance this method of transformation, to ensure that the lazy single-case thread safety

1, on the GetInstance method plus synchronization

1  Public Static synchronized Singleton getinstance () {  2          ifnull) {    3              New  Singleton ();   4          }     5         return Single ;   6 }

2. Double check Lock

1  Public StaticSingleton getinstance () {2         if(Singleton = =NULL) {    3             synchronized(Singleton.class) {    4                if(Singleton = =NULL) {    5Singleton =NewSingleton (); 6                }    7             }    8         }    9         returnSingleton; Ten}

3. Static internal class

  

1  Public classSingleton {2     Private Static classLazyholder {3        Private Static FinalSingleton INSTANCE =NewSingleton (); 4     }    5     PrivateSingleton () {}6      Public Static FinalSingleton getinstance () {7        returnlazyholder.instance; 8     }    9}

Static inner classes are better than 1 or 2, which enables thread safety and avoids the performance impact of synchronization

1  PackageCom.singleton;2 3 //lazy Singleton class that instantiates itself the first time it is called4 //but the lazy singleton implementation does not take into account the thread security problem, it is thread insecure, the concurrency environment is likely to appear multiple singleton instances5 //Why is there a thread safety problem? 6 //when multiple threads go to call class.getinstance, there is no instance in thread 1 's own memory space, so a new one is created, thread 2 goes to call instance, and creates a7 8 //There are three ways to improve: 1. Add synchronization on the GetInstance Method 2. Double check lock 3. Static inner class (this is better)9  Public classSingletonlazy {Ten     PrivateSingletonlazy () { One     } A  -     //when the class is initialized, the member variable is not assigned a value (lazy) and must wait until the call getinstance to create the instance -     /*private static Singletonlazy singleton = null; (This cannot be final, initially null, plus final, point cannot be changed, it is always null) the  - //Static Factory method - Public static Singletonlazy getinstance () { - if (singleton = = null) { + singleton = new Singletonlazy (); -         } + return singleton; A     }*/ at  -     //static inner class mode, when the Singletonlazy class is initialized, no member variable can be initialized -     //when GetInstance is called, the Lazyholder is loaded via the ClassLoader, and the Lazyholder Singleton instance is loaded -     //because the way the ClassLoader is thread-safe, this is also thread-safe -     Private Static classLazyholder { -         Private Static FinalSingletonlazy INSTANCE =NewSingletonlazy ();//(plus final, will not be modified after creation) in     } -  to      Public Static FinalSingletonlazy getinstance () { +         returnlazyholder.instance; -     } the } *     

Two, a hungry man type single case
1 //a hungry man Singleton, which has been instantiated by itself when the class is initialized2 //When this class is actually called, the initialization of this class is done, and the initial value is assigned to the static member variable .3 //when the getinstance is guaranteed, a single case already exists.4 //Why is this thread-safe? 5 //conjecture: The load initialization of a class will only be loaded once, Singletonhungry will only be created once, (plus final, will not be modified after creation) When more than one thread calls the Class.getinstance method, getinstance does not create it, but instead creates it directly to you, so I get the same instance (a reference variable) .6  Public classSingletonhungry {7     Private Static FinalSingletonhungry Singleton =Newsingletonhungry ();8     9     Privatesingletonhungry () {};Ten      One      Public Staticsingletonhungry getinstance () { A         returnSingleton; -     } -}

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

Three, a hungry man type and lazy type difference:

A hungry man is the class once loaded, the singleton initialization is completed, to ensure that the getinstance, the singleton is already exist,

And lazy idle, only when the call getinstance, only to initialize the singleton

In addition differentiates the following two ways from the following two points:

1. Thread Safety:

A hungry man is inherently thread-safe and can be used directly for multithreading without problems.

The lazy type itself is non-thread-safe, in order to achieve thread safety there are several ways to write, respectively, the above 1, 2, 3, these three implementations in the resource load and performance of some differences.



2. Resource Loading and performance:

A hungry man a static object is instantiated at the same time as the class is created, and will occupy a certain amount of memory regardless of whether the singleton will be used later, but correspondingly, the speed will be faster on the first call because its resources have been initialized,

And the lazy type as the name implies, will delay loading, in the first use of the singleton when the object will be instantiated, the first call to do the initialization, if you want to do more work, performance will be somewhat delayed, and then the same as the A Hungry man type.

There are some differences between the three implementations of 1, 2 and 3,

1th, in the method call added synchronization, although thread security, but each time to synchronize, will affect performance, after all, 99% of the case is not required to synchronize,

2nd, two null checks were made in getinstance to ensure that only the first invocation of the singleton will be synchronized, which is also thread-safe, while avoiding the performance loss of each synchronization

3rd, using the ClassLoader mechanism to ensure that there is only one thread when initializing instance, so it is thread-safe, and there is no performance loss, so I tend to use this one .

Java design pattern-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.