Single-piece mode (Singleton pattern) (i): Introduction to Single-piece mode

Source: Internet
Author: User
Tags volatile
I. Intention


single-piece mode (also known as a singleton pattern) ensures that a class has only one instance and provides a global access point.


Second, applicability

1. When a class can have only one instance and the customer can access it from a well-known access point.
2. When this unique instance should be extensible through subclasses, and the customer should be able to use an extended instance without changing the code.

third, the structure


four, the single piece mode's classical realization


Use Java to implement the single example pattern as follows:

Package Com.pattern.singleton;

public class Singleton
{
	private static Singleton uniqueinstance = null;

	Other useful instance variables
	
	//constructs are private, so it is not possible to create more than one instance private
	Singleton ()
	{
		//Initialize other instance variables
	}

	public outside the class Static Singleton getinstance ()
	{
		if (uniqueinstance = null)
		{
			uniqueinstance = new Singleton (); c23/>} return
		uniqueinstance
	}
}

This "singleton" is produced only when an instance of this class is first used, otherwise it is never generated, which is "deferred instantiation (lazy Instantiaze)";


v. Handling Multithreading


You can see that in the case of multithreading, the GetInstance method mentioned above may return different instances (for example, two threads can simultaneously determine that uniqueinstance is null and then produce two different instances), and in order to solve this situation, you might use the following methods:


1. Use the Synchronized keyword to turn the getinstance () method into a synchronous method

	public static synchronized Singleton getinstance ()
	{
		if (uniqueinstance = = null)
		{
			uniqueinstance = new Singleton ();
		}
		return uniqueinstance;
	}
Using synchronized can force each thread to enter the method before it has to wait for the other thread to leave the method (synchronized locks the corresponding class object), and this concurrency control method provided by Java can be Can severely degrade performance: Synchronization is required only the first time the getinstance () method is executed, and each time the method is invoked, synchronization becomes cumbersome (parallel execution to serial execution), and performance is significantly reduced if the getinstance () needs to be executed frequently.


2. Use "eagerly" to create an instance without delaying the instantiation

public class Singleton
{
	private static Singleton uniqueinstance = new Singleton ();
	Private Singleton ()
	{
		//other
	}
         //The unique singleton instance public
	static Singleton GetInstance was created when the JVM loaded the class  ( )
	{return
		uniqueinstance;
	}
}

The creation of a single piece during static initialization ensures thread safety. But if the object is very resource-intensive and does not use it during the execution of the program, it can cause a waste of resources.



3. Use "Double check plus lock" to reduce the usage of sync in getinstance ()


Using double check lock (double-checked locking), first check that the instance has been created, and if it has not been created, to synchronize, so that both the delay instantiation and the performance degradation caused by the multithreaded synchronization synchronized are avoided. is a good way to solve it.

public class Singleton
{
	private volatile static  Singleton uniqueinstance = null;
	Other
	
	private Singleton ()
	{
		//other
	} public

	static  Singleton getinstance ()
	{
		if ( Uniqueinstance = = null)
		{
			synchronized (singleton.class)
			{
				if (uniqueinstance==null)
				{
					uniqueinstance = new Singleton ();
		}} Return uniqueinstance
	}
}
Volatile keywords ensure that when uniqueinstance variables are initialized to singleton instances, multiple threads handle uniqueinstance variables correctly.

Note: Double check locking does not apply to versions 1.4 and earlier, and many JVM implementations of the volatile keyword in 1.4 and earlier will result in double check plus lock invalidation.


Vi. Other


1. In many cases, such as: thread pool, log object, database connection, etc., we need an object or need to control the number of instances, should use the singleton mode.


2. Before Java 1.2, the garbage collector causes a single piece to be purged as garbage when there is no global reference, so that a new instance is generated when the getinstance () method is invoked, and everything goes back to the original setting, and the singleton mode makes no sense. Therefore, a single piece registry must be established to prevent the garbage collector from withdrawing the single piece.


3. Because each classloader has its own namespace, different classloader may load the same class, so when using a single piece mode, multiple ClassLoader may have the opportunity to create their own singleton instances, the solution is to specify the class loader by itself and specify the same classloader.


4. It is best not to inherit a single piece of class. Because a single piece of the constructor must be changed to public or protected, it is not a real single piece.


5. Global variables and single-piece mode:

In Java, a global variable is basically a static (static) reference to an object (in fact, there is no concept of a global variable like C + + in Java), and if you assign an object to a global variable, you must create the object at the beginning of the program instead of delaying the instantiation. May cause waste of resources, the single piece mode can implement delay instantiation; Global variables can provide global access but cannot ensure that there is only one instance, with many global variables pointing to many small objects can cause namespace (namespace) pollution, and single pieces discourage such phenomena, but single pieces can still be abused.



Reprint please indicate the source: http://blog.csdn.net/jialinqiang/article/details/8847672

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.