Singleton mode analysis code optimization, Singleton Mode

Source: Internet
Author: User

Singleton mode analysis code optimization, Singleton Mode

The Singleton mode is one of the 23 design patterns and is a relatively simple design pattern. It aims to return the same object no matter how many calls, it features privatization of constructors.

It can be divided into two structures: lazy and ELE. Me. They have their own advantages and disadvantages. Let's start with the following code:

public class Single {    private static Single single = new Single();    private Single() {    }    public Single getInstance() {        return single;    }}

The above program shows that although the goal of loading the same object is indeed achieved, the single object will be created when the program is loaded, when this class has multiple such methods, we may not use most of the single examples of this object, which will cause a waste of memory. So there is a lazy Singleton mode. The Code is as follows:

public class Single {    private static Single single = null;    private Single() {    }    public Single getInstance() {        if(single==null){            single = new Single();        }        return single;    }}

In this way, it will be new only when we actually call this object, but this is a problem.

When two threads call the second part of the code during the first loading, two different objects will be generated, so the thread is not secure, at this time, we will think of adding a lock to this method. The code after the lock is as follows:

public class Single {    private static Single single = null;    private Single() {    }    public synchronized Single getInstance() {        if (single == null) {            single = new Single();        }        return single;    }}

This does ensure thread security, but it takes a long time to call this method when many things need to be executed in the lock method, which is fatal to the server, because if a thread has been calling this method, other threads cannot be called and the server is blocked, the upgraded code is as follows:

public class Single {    priate static Single single = null;    private Single() {    }    public Single getInstance() {        if (single == null) {            synchronized (Single.class) {                single = new Single();            }        }        return single;    }}

After careful observation, it is found that this is not locked. When two threads reach the getInstance () method if for the first time, one of them must be blocked. After the other is executed, blocking this thread will no longer judge whether it is null, or create an object. In this way, multiple objects are generated and then upgraded. The Code obtained is as follows:

public class Single {    private static Single single = null;    private Single() {    }    public Single getInstance() {        if (single == null) {            synchronized (Single.class) {                if (single == null) {                    single = new Single();                }            }        }        return single;    }}

In this way, the above problem will not occur, and only lock once, because when this method is re-executed for the second time, if judgment will be skipped, and single will be returned directly without being locked, the execution efficiency is also high.

But even so, there is still a problem, because we are not sure whether to assign a value to the object in the memory or create the object first, therefore, the second program may get half of the initialization object. After jdk1.5, we can use the volatile keyword to avoid this situation. The Code is as follows:

public class Single {    private static volatile Single single = null;    private Single() {    }    public Single getInstance() {        if (single == null) {            synchronized (Single.class) {                if (single == null) {                    single = new Single();                }            }        }        return single;    }}

However, this situation is rarely used. I am only here to learn about it.

 


How to write the singleton mode code

Singleton is one of the most common design patterns and is used by most systems to maintain the only instance in the system.
It can be divided into the eager mode. The sample code is as follows:
Java code
1. class EagerSingleton {
2. private static final EagerSingleton m_instance = new EagerSingleton ();
3. private EagerSingleton (){}
4. public static EagerSingleton getInstance (){
5. return m_instance;
6 .}
7 .}
Class EagerSingleton {
Private static final EagerSingleton m_instance = new EagerSingleton ();
Private EagerSingleton (){}
Public static EagerSingleton getInstance (){
Return m_instance;
}
}
And lazy mode. The sample code is as follows:
Java code
1. class LazySingleton {
2. private static LazySingleton m_instance = null;
3. private LazySingleton (){}
4. public synchronized static getInstance (){
5. if (m_instance = null ){
6. m_instance = new LazySingleton ();
7 .}
8. return m_instance;
9 .}
10 .}
Class LazySingleton {
Private static LazySingleton m_instance = null;
Private LazySingleton (){}
Public synchronized static getInstance (){
If (m_instance = null ){
M_instance = new LazySingleton ();
}
Return m_instance;
}
}
In java source code, Runtime. getRuntime () is an example of a singleton.
The spirit of Singleton mode is to maintain an instance in the entire system and promote it. If multiple examples need to be maintained in a system, the multiton mode is generated ).
In Multiton mode, multiple examples are retained by clustering objects, and the required instances are returned based on client parameters.
The sample code is as follows:
Java code
1. class Multiton {
2. private final int INSTANCE_SIZE = 10;
3. private static Map instances = new HashMap (INSTANCE_SIZE );
4. private String name;
5. private Multiton (){}
6. private Multiton (String name ){
7. this. name = name;
8 .}
9. public synchronized st ...... remaining full text>

How to write the code in java Singleton mode?

I have pasted my article from my blog. I should have a clear explanation of the singleton mode:
The Singleton mode is very common in our daily projects. When we need such an object in the project, this object can only have one instance in the memory, in this case, we need to use a singleton.

Generally, the singleton mode includes the following:

1. Hunger-type Singleton

Public class Singleton {
Private Singleton (){};
Private static Singleton instance = new Singleton ();
Public static Singleton getInstance (){
Return instance;
}
}

This is the simplest Singleton, which is the most common and reliable! Its only drawback is that it cannot complete delayed loading-that is, when the system has not used this Singleton, the singleton will be loaded into the memory.
Here we can perform a test like this:

Modify the above Code:

Public class Singleton {
Private Singleton (){
System. out. println ("createSingleton ");
};
Private static Singleton instance = new Singleton ();
Public static Singleton getInstance (){
Return instance;
}
Public static void testSingleton (){
System. out. println ("CreateString ");
}
}

We test it in another test class (in this example, all tests passed Junit)

Public class TestSingleton {
@ Test
Public void test (){
Singleton. testSingleton ();
}
}

Output result:

CreateSingleton
CreateString

We can note that in this Singleton, even if we do not use the singleton class, it is still created. This is of course what we do not want to see, so we have the following Singleton.

2. Lazy Singleton

Public class Singleton1 {
Private Singleton1 (){
System. out. println ("createSingleton ");
}
Private static Singleton1 instance = null;
Public static synchronized Singleton1 getInstance (){
Return instance = null? New Singleton1 (): instance;
}
Public static void testSingleton (){
System. out. println ("CreateString ");
}
}

Synchronization is required when the preceding Singleton obtains an instance. If synchronization is not added, when thread 1 completes the create Singleton operation in a multi-threaded environment, before assigning values, thread 2 may judge
The disconnected instance is empty. At this time, thread 2 also exists.

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.