Java design mode-Simple interest mode

Source: Internet
Author: User
Tags switches

Single-Case mode

As an object's creation mode, the singleton pattern ensures that one of its classes has only one instance , and instantiates itself and provides this instance to the entire system, which is called a singleton class. 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

The following look at the three ways of the singleton pattern, in addition to the three kinds of writing, static inner class, static code block way, enum enumeration way can also, but similar, these three ways do not write.

The first statement is that in our project we do not have to use lazy-type because there is a lock in the use of the place there is inefficient existence;

A Hungry man type

As the name implies, a hungry man-style, is the use of the class, regardless of whether the class is not a single case, all directly create a singleton class, look at the A Hungry man style of writing:

 Public class Singleeager {        publicstaticnew  Singleeager ();          Public Static Singleeager getinstance ()    {        return  se;    }}

This is the A Hungry man style of the single-case pattern, but also a more common way of writing. Does this kind of writing create competition and lead to thread safety issues? The answer is no.

One might find it strange: line 3rd, the CPU executes thread A, instantiates a eagersingleton, no instantiation is complete, the CPU switches from thread A to thread B, and thread B instantiates the Eagersingleton at this point, Then Eagersingleton was instantiated two times, there are two memory addresses, not on the thread security problem?

It doesn't matter, we don't have to worry about it at all, the JDK has helped us think of it. Java Virtual machine 2:java memory area and objects, the article can look at the object creation this part, not written in detail, in fact, "the virtual machine uses the CAS with the failure retry to ensure that the update update operation of the atomicity and Tlab two ways to solve the problem."

Lazy type

Similarly, as the name implies, this person is lazy, only when the Singleton class used to create this singleton class, look at the lazy style of writing:

 public  class   lazysingleton{ private  static  Lazysingleton instance = null         ;  private   Lazysingleton () {} /span>public  static   Lazysingleton getinstance () { if  (Insta nce = = null  ) instance  = new   Lazysingleton ();     return   instance; }}

This is basically not used, because it is a thread-unsafe way of writing. Imagine that thread a first calls the GetInstance () method, the code goes to line 12th, the thread switches to thread B at this point, thread B goes to line 12, and sees that instance is null, a new Lazysingleton comes out, then switches back to thread A, thread a continues to go, Also new a lazysingleton out. Thus, the Singleton class Lazysingleton has two references in memory, which violates the original meaning of the singleton pattern.

Some people might think that the time slice of the CPU will be shorter than the getinstance () method to switch threads with just one judgment. The problem is, in case thread A calls lazysingleton.getinstance () has executed other code before, it is normal to go to line 12 when the time slice is over.

Double check lock "In fact, this place is called double-checked lazy simple interest mode with lock"

Since the lazy type is non-thread-safe, it needs to be improved. The most direct idea is that the GetInstance method to lock not good, but we do not need to lock the method all ah, just need to give a part of the method to lock the good.

The purpose of the double check is to improve the efficiency, when the first thread creates an instance object, the thread behind it passes through to determine whether the first is null, and it can not go into the lock code area directly;

Based on this consideration, the notation of double check lock (double check lock, short DCL) is introduced:

 Public classdoublechecklocksingleton{Private StaticDoublechecklocksingleton instance =NULL; PrivateDoublechecklocksingleton () {} Public StaticDoublechecklocksingleton getinstance () {if (instance = = NULL)        {            synchronized(Doublechecklocksingleton.class)            {                if (instance = = NULL ) instance=NewDoublechecklocksingleton (); }        }        returninstance; }}

Is it not thread-safe to have a double check lock? Yes, as for why, it is advisable to analyze the style of double check lock by analyzing the way of lazy writing.

Thread A calls the Doublechecklocksingleton.getinstance () method for the first time, walks 12 lines, determines that instance is null, enters a synchronous code block, and the thread switches to thread B. Thread B calls the Doublechecklocksingleton.getinstance () method, because the code outside the synchronization code block is executed asynchronously, so thread B walks 12 lines, judging that instance is null and waiting for the lock. The result is that thread a instantiates a Doublechecklocksingleton, releases the lock, and thread B obtains the lock into the synchronization code block, judging that the instance is not NULL at this time, and does not instantiate Doublechecklocksingleton. Thus, the Singleton class guarantees that there is only one copy in memory.

The application and interpretation of singleton pattern in Java

Runtime is a typical example of the JDK API's interpretation of this class "Every Java application has a runtime class instance that enables the application to connect to the environment it is running, and the current runtime can be obtained through the GetRuntime method." The application cannot create its own instance of the runtime class. "There are two points in this passage that are important:

1. Each application has a runtime class instance

2. The application cannot create its own instance of the runtime class

Only one, can't create it yourself, is it a typical singleton pattern? Take a look at the runtime class's notation:

public class Runtime {    private static Runtime currentruntime = new Runtime ();//Use a hungry man    /**     * Returns t He runtime object associated with the current Java application.     * Most of the methods of class <code>Runtime</code> is instance      * methods and must be invoked with Respec T to the current runtime object.      *      * @return The  <code>Runtime</code> object associated with the current     *          Java Application.     *    /public static Runtime GetRuntime () {     return currentruntime;    }    /** Don ' t let anyone else instantiate this class *    /Private Runtime () {}    ...}

The back is not sticky, it is enough to see runtime using the GetRuntime () method and let the construction method private Guarantee program only one runtime instance and runtime instance can not be created by the user.

Advantages of Singleton mode

As an important design pattern, the advantages of the singleton pattern are:

1, control the use of resources, through thread synchronization to control the concurrent access to resources

2, the production of control cases, in order to achieve the purpose of saving resources

3, control the sharing of data, in the condition of not establishing a direct association, let a number of unrelated processes or threads to achieve communication between

Java design mode-Simple interest 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.