Java design pattern-Singleton mode

Source: Internet
Author: User
Tags volatile

Singleton pattern Definition

Make sure that there is only one instance of a class, and instantiate it yourself and provide this instance to the entire system, which is called a singleton class and provides a method for global access. Singleton mode is an object-creation pattern.

Implementation steps

(1) defining static Private member variables

(2) Create a unique instance (multiple implementations)

(3) Define private constructors to ensure that objects cannot be created externally by using the New keyword

(4) provides a static method for externally acquiring a singleton object

Implementation mode A hungry man-type singleton class

The A hungry man Singleton class is the simplest singleton class that defines a static private member variable that creates a singleton object when the class loads. The A hungry man singleton is thread-safe and does not occur when multiple singleton objects are created.

Code implementation
/*** A hungry man-type singleton class * @create 2018-04-12 17:05 **/ Public classEagersingleton {//defining static Private member variables, creating singleton objects    Private StaticEagersingleton instance =NewEagersingleton (); //define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateEagersingleton () {}//provides a static method for externally acquiring a singleton object     Public StaticEagersingleton getinstance () {returninstance; }}

Advantages and Disadvantages

Pros: Thread safety, where multiple instance objects are not created under multithreading.

Cons: Lazy loading is not implemented, and a singleton object is initialized when the class is loaded, which may be a long load time.

Lazy single-Case class

Lazy Singleton is also a classic way to implement a single case, the singleton object is not created when the class is loaded, but is created at the first call to the GetInstance method, which implements lazy loading, but in the case where multiple singleton objects are created under multithreading.

Non-thread-safe Code implementation
/*** Non-thread-safe lazy Singleton class * @create 2018-04-12 22:14 **/ Public classLazysingleton {//defining static Private member variables    Private StaticLazysingleton instance =NULL; //define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateLazysingleton () {}//provides a static method for externally acquiring a singleton object     Public StaticLazysingleton getinstance () {if(NULL==instance) {            //creating Singleton ObjectsInstance =NewLazysingleton (); }        returninstance; }}

Advantages and Disadvantages

Pros: Lazy Load implementation

Cons: Non-thread safe, does not work under multithreading

Thread-Safe Code implementation
/*** thread-Safe lazy Singleton class * @create 2018-04-12 22:14 **/ Public classLazysingleton {//defining static Private member variables    Private StaticLazysingleton instance =NULL; //define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateLazysingleton () {}//When you create an instance object, you add the thread lock, which enables threading security     Public Static synchronizedLazysingleton getinstance () {if(NULL==instance) {            //creating Singleton ObjectsInstance =NewLazysingleton (); }        returninstance; }}

Advantages and Disadvantages

Pros: Lazy loading, thread safety.

Disadvantage: Because the GetInstance method is added to the thread lock, each time the method is called, it will be locked, in the multi-threaded environment, the operating efficiency is very low.

It can be optimized in this way, where the line Cheng loads the place where the singleton object was created, rather than adding it directly to the GetInstance method.

Optimized code:

 PackageCom.lnjecit.singleton;/*** thread-Safe Lazy Singleton class * * @create 2018-04-12 22:14 **/ Public classLazysingleton {//defining static Private member variables    Private StaticLazysingleton instance =NULL; //define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateLazysingleton () {}//When you create an instance object, you add the thread lock, which enables threading security     Public StaticLazysingleton getinstance () {if(NULL==instance) {            synchronized(Lazysingleton.class) {                //creating Singleton ObjectsInstance =NewLazysingleton (); }        }        returninstance; }}

This approach can improve operational efficiency at a point, but it is still possible to create multiple singleton cases in multithreaded situations, and when instance is null, multiple threads access the GetInstance method at the same time, because instance is null, So the instance object is created,

Causes multiple instances to appear.

Dual Lock Code implementation
/*** Double check lock single class * @create 2018-04-12 22:14 **/ Public classLazysingleton {/*** Define static Private member variables, * Use the volatile keyword modifier to ensure thread visibility, and when one thread modifies the instance object, other threads can see the modified value*/    Private volatile StaticLazysingleton instance =NULL; //define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateLazysingleton () {}//When you create an instance object, you add the thread lock, which enables threading security     Public StaticLazysingleton getinstance () {if(NULL==instance) {            synchronized(Lazysingleton.class) {                if(NULL==instance) {                    //creating Singleton ObjectsInstance =NewLazysingleton (); }            }        }        returninstance; }}

Pros and cons

Pros: Lazy loading, thread safety.

Cons: The Volitile keyword masks the JVM's optimization of the code, which can lead to inefficient operation.

Internal Static class

A hungry man-type singleton class can not be lazy loading, lazy-type need to lock, judge and other ways to ensure thread safety, the implementation process cumbersome. Adding an internal static class to a single case reduces the process of locking and judging, so lazy loading and thread safety can be achieved without compromising operational efficiency.

Implementation code
/*** Static Inner class * @create 2018-04-12 17:05 **/ Public classSingleton {//define private constructors to ensure that external Eagersingleton instance objects cannot be created with the New keyword    PrivateSingleton () {}Private Static classSingletonholder {//creating Singleton Objects        Private Static FinalSingleton INSTANCE =NewSingleton (); }    //provides a static method for externally acquiring a singleton object     Public StaticSingleton getinstance () {returnsingletonholder.instance; }}

Advantages and Disadvantages

Pros: Lazy loading, thread safety.

Disadvantages:

Application Scenarios

Please refer to:

7420889

14160941

Resources

1, 7420886

Java design pattern-Singleton mode

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.