Singleton of [Java] design patterns (singleton)

Source: Internet
Author: User

In the daily work, there are many objects, we only need one. For example: thread pool, cache, registry, etc. If multiple instances are produced, many problems can result, such as abnormal program behavior, excessive resource usage, and so on. This requires controlling the construction of an object so that it can produce only one object. This is the design pattern to be talked about-Singleton (singleton).


Definition of a singleton pattern: Make sure that only one class has one instance and provides a global access point .


So, how do you implement Singleton mode so that a class can produce only one object? Take a look at the following implementations:

public class Singleton {private static Singleton s;private Singleton () {}public static Singleton getinstance () {if (s = = n ull) {s = new Singleton ();} return s;}}

you may have read the code above. That's right! We can set the class's constructor to private access so that other classes cannot arbitrarily create objects of that class. Then we apply a static class object as a unique object and as a global access point.


Clone () method

One more thing to note: the Clone () method of the class . For example, subclasses should override this method if the base class implements the Cloneable interface. Prevents the object of the class from being copied, destroying the singleton attribute. Of course, there should be a flexible use of various methods in the application to prevent the various situations of clone ().


Multithreaded Access Singleton method

For the above implementation, if it is accessed in multiple threads, it can cause problems.

public class Singleton {private static Singleton s;private Singleton () {}//Multiple instances may occur if multiple threads are concurrently accessed. public static Singleton getinstance () {///First time initialization, multiple threads execute "if (s = = null)" At the same time, judging the result is true, so the following actions are performed: "s = new Singleton ()", which throws Occurrences of multiple instances. if (s = = null) {s = new Singleton ();} return s;}}

so how to solve the problem of single mode in multi-threaded program?

Scenario 1:

Turn getinstance () into a synchronous (synchronized) method, and a multi-threaded disaster can be easily solved.

public class Singleton {private static Singleton s;private Singleton () {}public static <span style= "color: #FF0000;" >synchronized</span> Singleton getinstance () {if (s = = null) {s = new Singleton ();} return s;}}

This program is not recommended! Because it only takes one time to initialize a singleton, doing so will make each call to the GetInstance method synchronous. is a huge nuisance to operational efficiency.


Scenario 2:

Create a singleton at static initialization.

public class Singleton {//Early initialization. When defined, it is initialized. private static Singleton s = new Singleton ();p rivate Singleton () {}public static Singleton getinstance () {return s;}}


This method can guarantee a single case. But when we design, we usually keep the principle of creating objects until we use them.


Scenario 3:

Use double check plus lock to reduce synchronization in getinstance ().

public class Singleton {private static Singleton singleton;private Singleton () {}public static Singleton getinstance () {if (singleton = = null) {synchronized (singleton.class) {<span style= "color: #FF0000;" >if (singleton = = null) {</span>  //must singleton = new Singleton ();}}} return singleton;}}
This will only be synchronized when the object is created for the first time, ensuring thread safety while ensuring execution efficiency.

I have been asked why I should judge if (Sinlenton = = null) in synchronized, and I personally understand that this is the reason:

If two threads are executed to the first if (singleton = = null) and both are true, this is always a line enters upgradeable into synchronized (Singleton.class) ... Part of the code and block another entry. When the first entry is completed and an instance singleton is successfully built, it is no longer blocked. Another thread will go into execution synchronized (singleton.class) ... Code (because it has executed the first singleton==null and is true). If no judgment is made inside, a singleton will be created again.
So it was once again judged.


Reference:

"Head First design mode"

Http://blog.csdn.net/natee/article/details/4408245#quote

Singleton of [Java] design patterns (singleton)

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.