Java Singleton class

Source: Internet
Author: User
Tags volatile

            Singleton class:

Key points of knowledge:

1, single class concept, characteristics

2, three kinds of single-class lazy, a hungry man, double locking example,

3, lazy, a hungry man differences and a summary of the Singleton class;

1, Concept:
In Java, the singleton pattern is a common design pattern, the singleton pattern is divided into three kinds: lazy type single case, a hungry man type single case, double check and lock single case three kinds.
Singleton mode has the following features:
1, the Singleton class can have only one instance. The constructor is Private
3, the Singleton class must provide this instance to all other objects. Public method

2, three types of singleton :

A Hungry man type:

1  Public classEagersingleton {2 3     Private StaticEagersingleton instance =NewEagersingleton ();4 5     /**6 7 * Private default construction child8 9      */Ten  One     PrivateEagersingleton () {} A  -     /** -  the * Static Factory method -  -      */ -  +      Public StaticEagersingleton getinstance () { -  +         returninstance; A  at     } -  -}

In the example, when the class is loaded, the static variable instance is initialized, and the private constructor of the class is called. In this case, the only instance of the Singleton class is created. A hungry man creates an object instance when the class is loaded.

A hungry man type is the space change time, when the class load will create an instance of the class, whether you do not use, first created, and then each time the call, there is no need to judge, save the running time.

Lazy Type:

1  Public classLazysingleton {2 3     Private StaticLazysingleton instance =NULL;4 5     /**6 7 * Private default construction child8 9      */Ten  One     PrivateLazysingleton () {} A  -     /** -  the * Static Factory method -  -      */ -  +      Public Static synchronizedLazysingleton getinstance () { -  +         if(Instance = =NULL){ A  atInstance =NewLazysingleton (); -  -         } -  -         returninstance; -  in     } -  to 

The Lazy Singleton class implementation uses synchronization for static factory methods to handle multi-threaded environments. The lazy type is not in a hurry to create an object instance. Will wait until you are ready to use an object instance, and you do not create an object instance when you mount the object.
 

Lazy-type is the time to change space, that is, every time to obtain an instance will be judged to see if it is necessary to create an instance, wasting judgment time. Of course, if no one ever uses it, it doesn't create an instance, saving memory space

Because the lazy implementation is thread-safe, this reduces the speed of the entire visit and is judged every time.

double check Lock : (version java5 and above)

The so-called "double check plus lock" mechanism, refers to: not every time into the GetInstance method need to synchronize, but first out of sync, enter the method, first check whether the existence of the instance, if not exist before the following synchronization block, this is the first check, into the synchronization block, again check if the instance exists, If it does not exist, an instance is created in the case of synchronization, which is the second check. In this way, you only need to synchronize once, which reduces the time wasted in the synchronization of multiple judgments. The use of "double check lock" approach to achieve, can be both thread-safe, but also can make the performance is not greatly affected

   The implementation of the double check lock mechanism uses the keyword volatile, which means that the value of a volatile variable is not cached by the local thread, and that all read and write to the variable is directly operating shared memory, ensuring that the variable is handled correctly by multiple threads.

1  Public classSingleton {2 3     Private volatile StaticSingleton instance =NULL;4 5     PrivateSingleton () {}6 7      Public StaticSingleton getinstance () {8 9         //Check that the instance exists before entering the following synchronization block if it does not existTen  One         if(Instance = =NULL){ A  -             //synchronization blocks, thread-safe creation instances -  the             synchronized(Singleton.class) { -  -                 //Check again if the instance exists, and if it does not exist, actually create the instance -  +                 if(Instance = =NULL){ -  +Instance =NewSingleton (); A  at                 } -  -             } -  -         } -  in         returninstance; -  to     } +  -}

This approach enables thread-safe creation of instances without much impact on performance. It is just the first time to create an instance of synchronization, the future does not need synchronization, thereby speeding up the speed of operation.

Tip: Because the volatile keyword may block out some of the necessary code optimizations in a virtual machine, it is not very efficient to run. It is therefore generally recommended that no special needs be used. In other words, although you can use the double check and lock mechanism to implement a thread-safe singleton, it is not recommended to be used extensively, depending on the situation.

3, a hungry man and lazy-type difference and summary

The difference between the two main points of two

1. Thread Safety:

A hungry man-type is thread-safe, can be used directly for multithreading without problems, lazy-style is not, it is thread insecure, if used for multithreading may be instantiated multiple times, lost the role of Singleton.

If you want to use the lazy type for multi-threading, there are two ways to ensure security, one is to synchronize the GetInstance method, and the other is to use the Singleton method before and after the double lock.

2. Resource loading:

A hungry man a static object is instantiated at the same time as the class is created, regardless of whether the singleton will be used later, it takes up a certain amount of memory, and the corresponding speed will be faster at the time of the call.

And the lazy type as the name implies, will delay the loading, in the first use of the singleton when the object will be instantiated, the first time off to initialize, if you want to do more work, performance will be some delay, after the same as the A hungry man-style.

Conclusion: The result shows that the singleton pattern provides an object-only access point for an object-oriented application, and the entire application can enjoy an instance object regardless of the function it implements.

Report:

Thread Safety:

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. or, the interface provided by a class or program is atomic to the thread, or the switch between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization, which is thread-safe.

Java Singleton class

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.