(3/23) Singleton design mode and 23 design modes

Source: Internet
Author: User

(3/23) Singleton design mode and 23 design modes
As the name implies, only instance objects exist in JVM.
The Singleton design mode is widely used and has the following advantages:

1. When an object is large and frequently used, you can save a lot of system overhead by using a single example.
2. After the new operation, you do not need to create a new one. This reduces the usage frequency of the system memory and reduces the garbage collection mechanism.

3. In some cases, when a class is required to control the global configuration, a single instance is required. (A country can only have one top leader. If you talk more, who will listen to it ?)

A simple lazy style:

Public class Single {private static Single s = null; // private static instance to prevent external reference, initial null, delayed loading of private Single () {}// return the instance public static Single getInstace () {if (s = null) s = new Single (); return s ;}// if the object needs to be used for serialization, in this way, the Object can be consistent before and after serialization. public Object readResolve () {return s ;}}

The above implementation method, once in A multi-threaded environment, there will be A security risk, A, B two threads, A judgment s = null, is preparing new, not new, switch to line B. After line B completes new, switch back to thread A and continue new, causing potential risks.

Primary Solution:

Added thread locks to ensure security.

<span style="white-space:pre"></span>public class Single {private static Single s = null;private Single(){}public synchronized static Single getInstace(){if(s==null)s = new Single();return s;}public Object readResolve(){return s;}}

This method solves the security problem, but it sacrifices a bit at the cost. Because of the insecure multithreading problem, the new
The process of the Instance Object occurs, so we only need to ensure the thread security when the first object is created.

After improvement:

Public static Single getInstace () {if (s = null) {// resolution efficiency synchronized (Single. class) {if (s = null) // solves the security problem s = new Single () ;}} return s ;}

Synchronized is added internally. That is to say, the lock is not required during the call, only when s is null and the object is created.To improve the performance.

It seems that the problem has been solved, but there may be potential risks.

The creation of objects in the Java command is separated from the value assignment operation, that is, s = new Single (); the statement is executed in two steps.
However, the JVM does not guarantee the order of the two. It is possible that the JVM allocates space first, then assigns a value to s, and then initializes the Single instance, which causes problems.

For example, two threads A and B

1. both A and B are judged by the first if to enter
2. Thread A first obtains the Lock Object, s = null, and executes s = new Single ();
3. However, the JVM thread allocates the blank memory of the Single instance and assigns the value s, but there is still initialization s, and thread A leaves synchronized.
4. Line B gets the lock object, but s at this time! = Null, so line B leaves
5. Call the getInstace () program because there is no initialization and a problem occurs.

Therefore, in a multi-threaded environment, the hidden danger of laziness is hard to eradicate, so development is generally not used, and the hunger style is used.
(The interview must be about the lazy style with high technical skills)

Hungry Chinese Style

public class Single {private static final Single s = new Single();public static Single getInstance(){return Single.s;}}

You can use internal classes to further maintain the Singleton.

public class Single {private Single(){}public static class SingleChild{private static Single s = new Single();}public static Single getInstance(){return SingleChild.s;}public Object ReadResolve(){return getInstance();}}


1. The Singleton design model seems simple, but it is not easy to implement. The Lazy design method must be used with caution. Development is not used, but it must be met. Interview

2. The use of synchronized must be considered as a component, so that it stays in the place where it should be. Do not ignore this. It solves the security problem, but sacrifices the efficiency.

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.