Java design pattern-Singleton mode

Source: Internet
Author: User
Tags volatile tutorialspoint

Single-Case mode

As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole. This class is called a singleton class.

Structure of the Singleton pattern
    • 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
A hungry man single-case class
 Package Com.tutorialspoint;  Public class Eagersinleton {    privatestaticnew  Eagersinleton ();     Private Eagersinleton () {}      Public Static Eagersinleton getinstance () {        return  instance;    }}

In the example above, when the class is loaded, the static variable instance is initialized, and the private constructor of the class is called. The only instance of the Singleton class is then created.

A hungry man type is actually a kind of comparative image appellation. Now that you are hungry, when you create an object instance, you are more anxious and hungry, so you create an object instance when you load the class.

Private Static New Eagersinleton ();

a hungry man-type is a typical space change time , when the class is loaded 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 single-Case class
 PackageCom.tutorialspoint; Public classLazysingleton {Private StaticLazysingleton instance =NULL; /** Private Default construction **/    PrivateLazysingleton () {}/** Static Factory method **/     Public Static synchronizedLazysingleton getinstance () {if(Instance = =NULL) {instance=NewLazysingleton (); }         returninstance; }}

The lazy Singleton class above implements synchronous use of static factory methods to handle multithreaded environments.

The lazy type is actually a kind of comparative image appellation. Now that you're lazy, you don't have to worry about creating an object instance. Will wait until immediately to use the object instance will be created, lazy people, always can not evade the time to really do the work, so when loading the object is not created object instance.

Private Static null;

The lazy type is the typical time to change space. every time you get an instance, you will be judged to see if you need to create an instance and waste your judgment. Of course, if no one ever uses it, it doesn't create an instance, which saves memory space.

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

Double check plus lock

This can be achieved by using double-check lock, which enables both thread safety and performance to be unaffected. So what is the "double check plus lock" mechanism?

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 implementation of the "double check plus lock" mechanism uses the keyword "volatile", which means "the value of a variable modified by Volatie will not be cached by the local thread, and all read and write to that variable is directly operating shared memory", ensuring that the variable is correctly available for multiple threads.

Note: In previous versions of java1.4, many JVM issues with the implementation of the volatile keyword would result in a "double check lock" failure, so the "double check lock" mechanism could only be used in versions Java5 and above.

 PackageCom.tutorialspoint; Public classSingleton {Private volatile StaticSingleton instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {//Check that the instance exists before entering the following synchronization block if it does not exist        if(Instance = =NULL ) {            //synchronization blocks, thread-safe creation instances            synchronized(Singleton.class) {                //Check again if the instance exists, and if it does not exist, actually create the instance                if(Instance = =NULL) {instance=NewSingleton (); }            }        }        returninstance; }}

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. Therefore, it is generally recommended that there is no special need, not to use, that is to say, although you can use the "double check lock" mechanism to achieve a single case of thread safety, but it is not recommended a large number of use, can be selected according to the situation.

According to the above analysis, the two common single-instance implementations have a small flaw, then there is a scheme, the ability to implement lazy loading, but also to achieve thread safety?

Lay Initialization Holder class mode

This pattern synthesizes the knowledge of Java class-level internal classes and multithreaded default synchronization locks, and ingenious colleagues implement lazy loading and thread safety.

What is a class-level inner class:

The class-level inner class refers to a member-style inner class that has a static adornment. If there is no static adornment, the member inner class is called an object-level inner class.

The class-level inner class is equivalent to the static component of its outer class, which has no dependencies on the object and the outer class object, so it can be created directly. An object-level inner class, however, is bound to an external object instance.

In a class-level inner class, you can define a static method. Only static member methods or static member variables in external classes can be referenced in a static method.

Class-level internal classes are equivalent to members of their external classes and are loaded only when they are first used.

Multithreading Default Sync Lock:

In the multi-threaded development, in order to solve the concurrency problem, the main use of synchronized to add mutual exclusion lock for synchronization control. In some cases, however, the JVM has implicitly performed synchronization for you, and these situations do not have to be synchronized with your own control. These situations include:

    1. When the data is initialized by a static initializer (in the case of a static field or an initializer in a static{} block)
    2. When you access the final field
    3. When an object is created before the thread is created
    4. When a thread can see the object it will be working on
Solution:

To implement thread safety very simply, you can use a static initializer, which can be used by the JVM to guarantee thread security. For example, the previous a Hungry man implementation method. But that's a waste of space? Because of this implementation, the object is initialized when the class is loaded, whether you need it or not.

If there is a way to get the class to not initialize the object when it is loaded, it solves the problem, and one possible way is to use class-level inner classes to create object instances in this class-level inner class, so that object instances are not created as long as the class-level inner class is not used. This allows for both lazy loading and thread safety.

 PackageCom.tutorialspoint; Public classSingleton {PrivateSingleton () {}/** Class-level inner class, which is a static member-style inner class, where an instance of an inner class has no binding relationship with an instance of an external class, and is loaded only when called, enabling lazy loading **/    Private Static classsingletonholder{/** Static initializer, guaranteed by the JVM for thread safety **/        Private StaticSingleton instance =NewSingleton (); }     Public StaticSingleton getinstance () {returnsingletonholder.instance; }}

When the getinstance () method is called for the first time, It reads singletionholder.instance for the first time, causing the Singletonholder class to initialize, and this class initializes its static domain when it is loaded and initialized, creating an instance of Singletion because it is static, so it is known that when the virtual machine loads the class Initialized once and is guaranteed to be thread-safe by a virtual machine.

The advantage of this pattern is that the getinstance () method is not synchronized and only performs a domain access, so deferred initialization does not add any access costs.

Singleton and enumeration

Single-element enumeration types have become the best way to implement Singleton. It is very simple to use enumerations to implement a singleton, just to write an enumeration type that contains a single element.

 package   Com.tutorialspoint;  public  enum   Singletonn {  * Defines an enumeration element that represents an instance of Singletionn *  */         Uniqueinstance;  /*   * Singleton can have its own action *  */ public   String Singletonoperation () {  //  function handling  return  "ssssssssssssssssssss" ; }}

The use of enumeration classes can be more concise single-instance control, and provide a free serialization mechanism, and by the JVM to provide a fundamental guarantee, the absolute prevention of multiple instantiation, is a more concise, efficient, secure way to implement a single case.

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.