Java Design Pattern---singleton mode

Source: Internet
Author: User

How to style a single case pattern

1. Lazy mode (thread insecure)

lazy mode: as the name implies is needed to use the time to instantiate;

thread Insecure: Imagine that two threads both run to an if statement that determines whether instance is equal to null, and instance is not created, then all two threads will create an instance (execute: Instance = new Singleton1), the requirement of Singleton mode is not satisfied at this time.

 PackageSingleton; Public classSingleton1 {PrivateSingleton1 () {}//private only intrinsic functions can call         Private StaticSingleton1 instance =NULL;  Public StaticSingleton1 getinstance () {if(Instance = =NULL) {instance=NewSingleton1 ();//constructors are declared private, only intrinsic functions can be called, ensuring that only one instance is created         }        returninstance; }
}

2. Lazy mode (thread safe)

Thread Safety: Add a sync lock (synchronized) to ensure thread safety. At this point, if two threads create an instance at the same time, because only one thread can get a synchronous lock at a time, when one thread is added to the synchronization lock, the other thread can wait. When the first thread discovers that the instance has not yet been created, it creates an instance. The first thread then releases the sync Lock, at which point the second thread can add a synchronous lock, but it finds that an instance has been created at this point and does not create an instance again. This ensures a single case pattern.

 PackageSingleton; Public classSingleton2 {PrivateSingleton2 () {}// Private only intrinsic functions can be called    Private StaticSingleton2 instance;  Public Static synchronizedSingleton2 getinstance () {//sync Lock To resolve thread synchronization issues        if(Instance = =NULL) {instance=NewSingleton2 ();//constructors are declared private, only intrinsic functions can be called, ensuring that only one instance is created        }       returninstance; }}

3. Lazy Mode ( double check lock)

Considering the 2nd method because locking is a time-consuming operation, we try to reduce the number of locks.

This method: If the instance has been created, return it directly, and if the instance is not created, then lock the thread to ensure that the instance is created again.

Note: Keyword volatile

the role of volatile : forcing each time to read the memory directly, prevent reordering, ensure that The value of the Voltile type once written to the cache will be immediately updated to main memory .

Because: In the Java multithreaded environment, each Java thread, in addition to the shared virtual machine stack and the Java heap, there is a separate private heap memory (by default, the size of 512KB, the thread is created when the assignment, you can adjust its default value by the-XSS option). Each thread runs independently of each other and is invisible to each other, leaving a copy of the main memory in the private heap memory of the thread, which is only interactive (copy/refresh) with memory only in the case of a specific requirement. In this case, there is a situation where an instance has been created on the private heap memory of a thread, because the thread has not yet interacted with the main memory, causing the instance to not exist on the main memory. This problem can be solved by using volatile at this time.

 PackageSingleton; Public classSingleton3 {PrivateSingleton3 () {}//private only intrinsic functions can be called    Private volatile StaticSingleton3 instance =NULL;  Public Static synchronizedSingleton3 getinstance () {//sync Lock To resolve thread synchronization issues        if(Instance = =NULL) {//lock time, reduce the number of locks            synchronized(Singleton3.class){                if(Instance = =NULL) {instance=NewSingleton3 ();//constructors are declared private, only intrinsic functions can be called, ensuring that only one instance is created                }            }        }        returninstance; }}

4. A Hungry man mode

A hungry man mode: relative to lazy mode, the A Hungry man mode is to create an instance when the class is loaded.

This approach avoids multi-threaded synchronization problems based on the classloder mechanism, and instance is instantiated when the class is loaded. Here are two ways to a hungry man the pattern.

 Package Singleton;  Public class Singleton4 {    privatestaticnew  Singleton4 ();       Private Singleton4 () {}      Public Static Singleton4 getinstance () {           return  instance;      }  }

 PackageSingleton; Public classSingleton5 {Private StaticSingleton5 instance =NULL; Static{instance=NewSingleton5 (); }       PrivateSingleton5 () {} Public StaticSingleton5 getinstance () {returnsingleton5.instance; }  }

5. Static Inner class

This approach also takes advantage of the classloder mechanism to ensure that only one thread is initialized instance, which differs from a hungry man mode in that a hungry man mode is instantiated as long as the Singleton class is loaded, and the instance is instanced (not reaching the lazy Loading effect), and this method is singleton class is loaded, instance is not necessarily initialized. Because the Singletonholder class is not actively used, the load Singletonholder class is displayed only if it is displayed by calling the GetInstance method, thus instantiating the instance. Imagine if instantiating instance is draining resources, I want him to delay loading, on the other hand, I don't want to instantiate when the singleton class loads, because I can't make sure that the Singleton class can be actively used in other places to be loaded, It is obviously inappropriate to instantiate instance at this time. This time, this way is quite reasonable compared to the A Hungry man mode.

 PackageSingleton; Public classSingleton6 {Private Static classSingletonholder {Private Static FinalSingleton6 INSTANCE =NewSingleton6 (); }    PrivateSingleton6 () {} Public Static FinalSingleton6 getinstance () {returnSingletonholder.instance;//Singleton mode deferred to singletonholder this class loads    }}

6. Enumeration

Enumeration: Not only does it avoid multithreading synchronization problems, but it also prevents deserialization from recreating new objects.

 Package Singleton;  Public enum Singleton7 {    INSTANCE;  }

Resources

    1. "Think in Java"
    2. "Head First design pattern"
    3. "The sword means offer"
    4. Http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html
    5. Http://www.tuicool.com/articles/uyEvaeQ

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.