Several implementations of Java singleton pattern

Source: Internet
Author: User

The singleton mode is used to ensure that the class is created only one instance of the class during runtime, and the singleton schema provides a globally unique access point to access the class instance, which is the GetInstance method.

In the case of Singleton mode, regardless of the implementation, it is only concerned with the creation of the class instance, and does not care about the specific business functions.

First Scenario: Lazy type

Lazy type of class is created in the GetInstance method, lazy is a typical time to change space, that is, every time the instance will be judged to see if it is necessary to create an instance, wasting judgment time. Of course, if there is no one to use, it will not create an instance, saving memory space

 Packagesingle case mode;/*** Lazy Type *@authorAdministrator **/ Public classSingleton1 {Private StaticSingleton1 uniqueinstance =NULL; PrivateSingleton1 () {} Public Static synchronizedSingleton1 getinstance () {if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton1 (); }        returnuniqueinstance; }    }

This lazy type is not synchronized, so the thread is unsafe and can be added synchornized to make thread safe:

 Public Static synchronized Singleton getinstance () {}

However, this reduces the overall access speed, and every time you have to judge, you can use "double check lock" to make the thread safe, but also to make performance is not greatly affected.

"Double check plus lock" refers to not every time into the GetInstance method need to synchronize, but first out of sync, enter the method after the first check the existence of the instance, if it does not exist to enter the following synchronization block, this is the first check, into the synchronization block, check again if the instance exists, but does not exist, Creates an instance in the case of synchronization, which is the second check. In this way, only one synchronization is required, which reduces the time wasted in the synchronization of multiple judgements, and is implemented as follows:

 Packagesingle case mode;/*** Double Lock lazy type *@authorAdministrator **/ Public classSingleton3 {Private volatile StaticSingleton3 instance =NULL; PrivateSingleton3 () {} Public StaticSingleton3 getinstance () {if(Instance = =NULL){            synchronized(Singleton3.class) {                if(Instance = =NULL) {instance=NewSingleton3 (); }            }        }        returninstance; }}

Second scenario: a Hungry man type

A hungry man type is a typical space change time, when the class loading will create a class instance, no matter you do not use, first created, and then each time electrophoresis, there is no need to judge, save the running time, a hungry man is thread-safe

 Packagesingle case mode;/*** A hungry man type *@authorAdministrator **/ Public classSingleton2 {Private StaticSingleton2 uniqueinstance=NewSingleton2 (); PrivateSingleton2 () {} Public StaticSingleton2 getinstance () {returnuniqueinstance; }}

A better way to implement a single example in Java:


Both of the above scenarios have some drawbacks, so is there a way to implement both lazy loading and thread safety?

To implement thread safety, you can use a static initializer, which can be used by the JVM to ensure thread security, such as the previous a Hungry man style, but in this way, it wastes a certain amount of space.

If there is a way to allow the class to be loaded without initializing the object, does it solve the problem? One possible approach is to use the inner class to create an object instance within the inner category, so that if it is not practical to this class-level inner class, the object instance will not be created, allowing for both lazy loading and thread safety.

The implementation is as follows:

 Packagesingle case mode;/*** thread-safe and efficient using internal static classes *@authorAdministrator **/ Public classSingleton4 {Private Static classsingletonholder{Private StaticSingleton4 instance =NewSingleton4 (); }        PrivateSingleton4 () {} Public StaticSingleton4 getinstance () {returnsingletonholder.instance; }}

PS: Not long ago to participate in the spring of cherish net, Java Development Engineer interview Youdao asked to thread-safe and efficient single-case mode, you can use the way of internal classes, unfortunately did not understand.

Several implementations of Java singleton pattern

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.