[Java] design pattern Singleton (single example)

Source: Internet
Author: User
Tags static class

In the daily work, there are many objects, we only need one. For example: thread pool, caching, registry, and so on. If you create multiple instances, you can cause many problems, such as abnormal program behavior, excessive use of resources, and so on. This requires controlling the construction of the object so that it can produce only one object. This is the design pattern--singleton (single example) to be talked about in this article.


Singleton schema Definition: Make sure that only one class has one instance and provides a global access point.


So how do you implement a single case pattern so that a class can only produce one object? Consider the following implementation:

public class Singleton {
	private static Singleton s;
	Private Singleton () {
	} public
	static Singleton getinstance () {
		if (s = = null) {
			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 create objects of that class at will. 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 copy, destroying the single instance attribute. Of course, in the application should be flexible use of various methods to prevent the various situations of clone ().


Multithreading Access Singleton method

The above implementation method, if accessed in multiple threads, may cause problems.

public class Singleton {
	private static Singleton s;
	Private Singleton () {
	}
	//Multiple instances may occur if multiple threads are accessing at the same time. Public
	static Singleton getinstance () {
		///When first initialized, multiple threads execute "if (s = = null)" At the same time, the results are true, so the following actions are performed: "s = new singlet On (), which causes multiple instances to appear.
		if (s = = null) {
			s = new Singleton ();
		}
		return s;
	}
}

So how to solve the problem of single case pattern in multithreaded program?

Programme 1:

GetInstance () into a synchronous (synchronized) method, multithreaded disaster can be easily resolved.

public class Singleton {
	private static Singleton s;
	Private Singleton () {
	} public
	
	static synchronized Singleton getinstance () {
		if (s = = null) {
			s = new Singleton ();
		}
		return s;
	}
}

The scheme is not recommended. Because it only takes one time to initialize a single instance, doing so will synchronize every time the GetInstance method is invoked. is a huge drag on operational efficiency.


Programme 2:

Create a single instance when statically initialized.

public class Singleton {
	//Early initialization. Initialize when defined.
	private static Singleton s = new Singleton ();
	Private Singleton () {
	} public
	static Singleton getinstance () {return
		s;
	}
}


This method can guarantee the single example. But we usually keep the principle of creating objects until we use them when designing.


Programme 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) {
				if (Singleton = null) {   //must
					Singleton = new Singleton ();
				}
			}
		}
		Return singleton
	}
}
This will only synchronize the first time an object is created, ensuring thread safety while ensuring execution efficiency.

Someone asked why to judge if (Sinlenton = null) again in synchronized, I personally understand this reason:

If all two threads have executed to the first if (singleton = null) and are true, there is always a line enters upgradeable into synchronized (Singleton.class) ... Part of the code and block another entry. After the first entry and successfully built an instance singleton, no longer blocks. Another thread will enter the execution synchronized (singleton.class) ... Code (because it has executed the first singleton==null and is true). If the inside is no longer judged, a singleton is created again.
So it was once again judged.


Reference:

Head of the design model

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

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.