"--singleton" (Java edition)

Source: Internet
Author: User
Tags volatile

1. Definition of a singleton pattern

Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

2. Characteristics of the Singleton mode

A singleton class can have only one instance.

The Singleton class must create its own unique instance.

The Singleton class must provide this instance to all other objects.

3. Java code for Singleton mode

The singleton pattern is divided into lazy (need to create objects) and a hungry man (create an object when creating an instance of the class).

4. A Hungry man type

In a static code block instance object

// in a static code block instance Object  Public class Singleton {
Private Static Singleton Singleton; Static { new Singleton (); } Public Static Singleton getinstance () { return Singleton; } Private Singleton () {}}

Property Instantiation Object

// a hungry man mode: Thread-safe, resource-intensive.  class  singletonhungry {
Private Static Final New singletonhungry (); Public Static singletonhungry getsingletontest () { return singletontest; } Private singletonhungry () {}}

Above, a hungry man as long as the class is called, an object is instantiated, which is very resource-intensive.

5. Lazy Type

Non-thread safe, only join the thread lock (synchronized keyword) to ensure thread safety.

//lazy mode: Need to add the thread lock (synchronized keyword), to ensure securityclassSingletonSlacker1 {
Private StaticSingletonSlacker1 Singleton; Public synchronized StaticSingletonSlacker1 getinstance () {if(Singleton = =NULL) {Singleton=NewSingletonSlacker1 (); } returnSingleton; } PrivateSingletonSlacker1 () {}}

Of course, this approach, while guaranteeing the security of threads, can only be called by one thread, and other threads must wait.

Thread Safety: Double check Lock (synchronous code block)

//lazy mode: Add double lockclassSingletonSlacker2 {
Private StaticSingletonSlacker2 Singleton; Public synchronized StaticSingletonSlacker2 getinstance () {if(Singleton = =NULL) { synchronized(Singleton.class) { if(Singleton = =NULL) {Singleton=NewSingletonSlacker2 (); } } } returnSingleton; } PrivateSingletonSlacker2 () {}}

6. Order reordering

In fact, creating an object often consists of three processes.
For Singleton = new Singleton (), this is not an atomic operation, including three procedures in the JVM.

1. Allocating memory to Singleton

2. Call the constructor of Singleton to initialize the member variables to form an instance

3. Point the Singleton object to the allocated memory space (singleton is not NULL after executing this step)

For order reordering in the JVM, we can use the volatile keyword to ensure thread safety.

classsingletonvolatile{//The role of volatile is to guarantee visibility, prohibit reordering, but not guarantee atomicity.     Private volatile StaticSingletonvolatile Singleton;  Public synchronized Staticsingletonvolatile getinstance () {if(singleton==NULL){            synchronized(Singletonvolatile.class){                if(singleton==NULL) {Singleton=NewSingletonvolatile (); }            }        }        returnSingleton; }    PrivateSingletonvolatile () {}}

Research is not deep, just learn Java, if there is anything wrong, also hope to point out errors, common improvement.

GitHub Address: Https://github.com/Yahuiya/PersonalNotes

"--singleton" (Java edition)

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.