cool hit counter Java Design Patterns - Singleton Pattern_Intefrankly

Java Design Patterns - Singleton Pattern

singleton model

as the creation mode of the object. The singleton pattern ensures that one of its classes has only one instance , and instantiates itself and makes this instance available to the entire system, the class is called a singleton class. The singleton model has the following characteristics.

1. Single instance class can only have one instance

2. The singleton class must create its own unique instance

3. The singleton class must provide this instance to all other objects

Here's a look at three ways to write the singleton pattern. In addition to these three, the static inner class way, the static code block way, and the enum enum way are all possible, but the differences are the same, and these three are left out.

First of all, for the record, we don't need to use the lazy style at all in our project, because where locks are used, they exist inefficiently.

starving-hands style

As the name implies, the Hungry Man style, which means that the singleton class is created directly when using the class regardless of whether or not the singleton part of the class is used, looks at how the Hungry Man style is written.

public class SingleEager {
    public static SingleEager se = new SingleEager();
    public static SingleEager getInstance()
        return se;


This is the way the Hungry Man singleton pattern is written, and is a relatively common way of writing it. Will this writing style create competition and raise thread safety issues? The answer is no.

Some may find it strange: line 3, the CPU executes thread A, instantiates an EagerSingleton, and without finishing instantiating it, the CPU switches from thread A to thread B. Thread B also instantiates this EagerSingleton at this point, and then the EagerSingleton is instantiated twice, with two copies of the memory address, so doesn't that have a thread safety problem?

That's okay, we don't need to worry about that at all, the JDK has thought of it for us. Java Virtual Machine 2: Java Memory Regions and Objects,The text can be seen in the section on object creation, Not written in great detail, in fact, it is" The virtual machine uses theCAS Paired with a failure retry to ensure atomicity of update update operations andTLAB Two ways to solve this problem"。


Again, as the name implies, this person is lazy and only creates the singleton class when it is used, look at the lazy way of writing.

public class LazySingleton
    private static LazySingleton instance = null;
    private LazySingleton()
    public static LazySingleton getInstance()
        if (instance == null)
            instance = new LazySingleton();
        return instance;

This writing style is basically not used, Because this is a thread non-safe way of writing。 just think!, threadsA Initial callgetInstance() approach, The code goes to the first12 go, Threads switch to threads at this pointB, threadsB walk towards12 go, see thatinstance benull, just (emphasis)new have a look atLazySingleton forth, Switch back to the thread at this pointA, threadsA Keep going., toonew have a look atLazySingleton forth。 thus, singleton class (computing)LazySingleton That's two references in memory., This goes against the singleton model The original intent of the。

One might wonder how short a CPU slice of time can be without the getInstance() method switching threads after executing only one judgment, right? The problem is, what if thread A has already executed other code before calling LazySingleton.getInstance(), and it's not unusual to go to line 12 just as the time slice is up.

Double-checked locks [actually, this place is called Double-checked lazy-boy monolithic model with locks]

Since the lazy style is non-thread safe, it needs to be improved. The most straightforward idea would be to just lock the getInstance method, but we don't need to lock all of the method, just part of it.

(a) The purpose of double-checking is to improve efficiency, so that when the first thread creates an instance object, later-entering threads can simply not have to walk into the locking code area by determining whether the first one is null.

With this in mind, the Double Check Lock (DCL) is introduced to write.

public class DoubleCheckLockSingleton
    private static DoubleCheckLockSingleton instance = null;
    private DoubleCheckLockSingleton()
    public static DoubleCheckLockSingleton getInstance()
        if (instance == null)
            synchronized (DoubleCheckLockSingleton.class)
                if (instance == null)
                    instance  = new DoubleCheckLockSingleton();
        return instance;

Is the double-check lock written in a thread-safe way?? yes, As to why, It may be useful to analyze lazybones The way the write method is analyzed for double-checked locks。

Thread A initially calls the DoubleCheckLockSingleton.getInstance() method, goes 12 lines, determines instance is null, and enters the synchronous code block, at which point the thread switches to thread B. Thread B calls the DoubleCheckLockSingleton.getInstance() method, and since the code outside the synchronous code block is still executed asynchronously, thread B goes 12 lines, determines instance is null, and waits for the lock. The result is that thread A instantiates a DoubleCheckLockSingleton, releases the lock, thread B gets the lock and enters the synchronization code block, determines that instance is not null at this point, and does not instantiate the DoubleCheckLockSingleton. In this way, the singleton class is guaranteed to have only one copy in memory.

Application and Interpretation of the Singleton Pattern in Java

Runtime is a typical example, Take a look.JDK API For an explanation of this class" everyoneJava The applications all have aRuntime class instance, Enabling applications to connect to the environment they run in, This can be done bygetRuntime method to get the current runtime。 Applications cannot create their ownRuntime class instance。", This paragraph, There are two important points:

1. Each application has an instance of the Runtime class

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

Is it typical of the singleton pattern to have only one and not be able to create it yourself? Take a look, the Runtime class is written.

public class Runtime {
    private static Runtime currentRuntime = new Runtime(); // Use the Hungry Man style

     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance 
     * methods and must be invoked with respect 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() {}


I won't paste the latter, it's enough to see that Runtime uses the getRuntime() method and makes the constructor private to ensure that there is only one instance of Runtime in the program and that the Runtime instance cannot be created by the user.

Benefits of the singleton pattern

As an important design pattern,Benefits of the singleton pattern have:

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

2. Control the generation of instances for the purpose of saving resources

3. Control the sharing of data and allow communication between multiple unrelated processes or threads without establishing a direct association

1、Mass Fantasia
2、Traditional low voltage appliances with trendy artificial intelligence
3、Capital Tendo Blockchain Future The Mechanics of Blockchain Operation
4、The big survey with a prize have you been infringed on your consumption this year
5、2018 Starting point of lithium intelligent manufacturing visit into Hongbao Technology high standards and strict requirements to build the first brand of lithium equipment

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送