"Singleton mode" and its application scenario in Java design pattern

Source: Internet
Author: User
Tags volatile

Reprint reference: http://www.cnblogs.com/V1haoge/p/6510196.html

The so-called Singleton, refers to a single instance, there is only one class instance, this singleton should not be controlled by the person, but should be limited by the code, mandatory Singleton.

Singleton has its own unique use scenario, generally for those business logic can only be limited to a single case, for example: similar to the existence of counters, and generally need to use an instance to record, if the multi-sample count will be inaccurate.

In fact, the single case is the obvious use of the situation, there is no previous learning patterns used in the complex scenes, as long as you need to use a singleton, then you use a single case, simple and easy to understand.

So I think the focus of the singleton pattern is not on the scene, but on how to use it.

1, the common singleton mode has two ways to create: the so-called hungry lazy and a hungry man type

(1) Lazy type

What is laziness? As the name implies, is not doing things, here is synonymous, lazy-type is not in the system to create a single instance of the class, but the first time when the use of instances to create.

See the code example below:

 Public classLhandanli {//define a private class variable to hold a singleton, the purpose of which is to refer to the external cannot directly get the variable, but to use the public method provided to get    Private StaticLhandanli dl =NULL; //defines a private constructor that is used only within a class, or that an instance of a singleton can only be created inside a singleton class    PrivateLhandanli () {}//define a common public method to return an instance of this class, because it is lazy and needs to be generated on the first use, so for thread safety, use the Synchronized keyword to ensure that only a single case is generated     Public Static synchronizedLhandanli getinstance () {if(DL = =NULL) {DL=NewLhandanli (); }        returnDL; }}

(2) A Hungry man type

What's The hunger? If you are hungry, you will eat fast. It is synonymous here: when you load a class, you create a singleton of the class and save it in the class.

See the code example below:

 Public classEhandanli {//The class variable instance is defined here and instantiated directly, and is instantiated and saved in the class when the class is loaded    Private StaticEhandanli dl =NewEhandanli (); //define an parameterless constructor for a singleton instance    PrivateEhandanli () {}//defines the public method that returns the created singleton     Public StaticEhandanli getinstance () {returnDL; }}

2. Double locking mechanism

What is double locking mechanism?

In the lazy-type implementation of the single-mode code, there is the use of synchronized keyword to synchronize to obtain an instance, to ensure the uniqueness of the Singleton, but the above code in each execution of the synchronization and judgment, will undoubtedly slow down the speed, the use of double locking mechanism just can solve the problem:

 Public classSlhandanli {Private Static volatileSlhandanli dl =NULL; PrivateSlhandanli () {} Public StaticSlhandanli getinstance () {if(DL = =NULL){            synchronized(Slhandanli.class) {                if(DL = =NULL) {DL=NewSlhandanli (); }            }        }        returnDL; }}

See the above code, there is no feeling very silent, double plus lock is not required two synchronized to lock it?

......

Actually, here double refers to the double judgment, and lock single refers to that synchronized, why to double judgment, in fact, very simple, the first judgment, if a singleton already exists, then no longer need to synchronize operation, but directly return to this instance, if not created, will enter the synchronization block, The purpose of the synchronization block is the same as before, in order to prevent two calls at the same time, resulting in multiple instances, with a synchronization block, only one thread can access the synchronization block content at a time, when the first call to the lock gets an instance, the instance is created, and all subsequent calls do not enter the synchronization block. The singleton is returned directly to the first judgment. As for the second judgment, the personal feeling is a bit of a search for a trap (looking for brilliant ideas).

However, with the use of double locking mechanism, the execution speed of the program has been significantly improved, do not need to synchronize lock every time.

In fact, I am most concerned about the use of volatile, the meaning of the volatile keyword is: The value of its modified variable is not cached by the local thread, all read and write to the variable is directly operating shared memory to implement, to ensure that multiple threads can correctly handle the variable. This keyword may block out some code optimization in the virtual machine, so its efficiency may not be very high, so, in general, do not recommend the use of double locking mechanism, as appropriate, the use of Nyaya!

3, class-Level internal class mode

A hungry man will take up more space, because it will be instantiated when the class is loaded, and the lazy type has a slow execution rate, double locking mechanism? There is a poor implementation of the problem, there is no perfect way to avoid these problems?

Seemingly, it is the use of class-level internal classes combined with multi-threaded default synchronization locks, while implementing lazy loading and thread safety.

 Public class Classinnerclassdanli {    publicstaticclass  danliholder{          Privatestaticnew  Classinnerclassdanli ();    }     Private Classinnerclassdanli () {}      Public Static Classinnerclassdanli getinstance () {        return  danliholder.dl;    }}

As in the code, the so-called class-level inner class, is a static inner class, this inner class and its external class does not have a dependency, loading the external class, and does not load its static internal class, only when the call occurs when the load, the load will create a singleton instance and return, Lazy loading is effectively implemented (deferred loading), and as for the synchronization problem, we use the same static initializer as the A hungry man, with the help of the JVM for thread safety.

In fact, using a static initializer creates an instance of the class when the class loads, but we explicitly place the creation of the instance in a static inner class, which causes the external classes to be loaded without instance creation, so that we can achieve our dual purpose: lazy loading and thread safety.

4. Use

The bean instance created in spring is a singleton mode by default.

"Singleton mode" and its application scenario in Java design pattern

Related Article

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.