About Singleton mode This is better than the above 1, 2, both to achieve thread safety and avoid the performance impact of synchronization.

Source: Internet
Author: User

In Java, the singleton pattern is a common design pattern, there are several types of single-instance pattern, here are three kinds: lazy type single case, a hungry man type single case, registration type single case.
The singleton mode has the following characteristics:
  1, the Singleton class can have only one instance.
  2, the Singleton class must create its own unique instance.
  3. The Singleton class must provide this instance to all other objects .
Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system. In a computer system, the driver objects of the thread pool, cache, log Object, dialog box, printer, and video card are often designed as singleton. These apps have more or less the functionality of the resource manager. Each computer can have several printers, but only one printer Spooler to prevent both print jobs from being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent a communication port from being called simultaneously by two requests. In short, the selection of Singleton mode is to avoid inconsistent state, to avoid long-running political.

Lazy Single-case

1 //Lazy Type Singleton class. Instantiate yourself at the first call2  Public classSingleton {3     PrivateSingleton () {}4     Private StaticSingleton single=NULL; 5     //Static Factory Method6      Public StaticSingleton getinstance () {7          if(single =NULL) {    8Single =NewSingleton (); 9          }    Ten         returnSingle ;  One     }   A}
Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope.

(In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )

However, the above-mentioned lazy singleton implementation does not take into account the thread safety problem, it is thread insecure, the concurrency environment is likely to have multiple singleton instances, to achieve thread safety, there are the following three ways, is to getinstance this method of transformation, to ensure that the lazy single-case thread safety, If you first contact the singleton mode, the thread safety is not very understanding, you can skip the following three strips, to see the A hungry man-type singleton, and then look back to consider the issue of thread safety:

1. Synchronize on the GetInstance method

1  Public Static synchronized Singleton getinstance () {  2          ifnull) {    3              New  Singleton ();   4          }     5         return Single ;   6 }  

2. Double check Lock

1  Public StaticSingleton getinstance () {2         if(Singleton = =NULL) {    3             synchronized(Singleton.class) {    4                if(Singleton = =NULL) {    5Singleton =NewSingleton (); 6                }    7             }    8         }    9         returnSingleton; Ten}

3. Static internal class

1  Public classSingleton {2     Private Static classLazyholder {3        Private Static FinalSingleton INSTANCE =NewSingleton (); 4     }    5     PrivateSingleton () {}6      Public Static FinalSingleton getinstance () {7        returnlazyholder.instance; 8     }    9}

This is better than the above 1, 2, both for thread safety and to avoid the performance impact of synchronization.

Two, a hungry man type single case

 //  A hungry man Singleton class. At class initialization, the  public  class   Singleton1 { private   Singleton1 () {}  private  static        Final  Singleton1 single = new   Singleton1 ();  //  static factory method  public  static   Singleton1      GetInstance () { return   single; }  } 

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

About Singleton mode This is better than the above 1, 2, both to achieve thread safety and avoid the performance impact of synchronization.

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.