Design pattern Comb-Singleton mode

Source: Internet
Author: User
Tags static class volatile

A concept Introduction:The so-called singleton mode, simply put, is to ensure that only one instance of a class exists throughout the application, and that it instantiates itself and provides this instance to the system as a whole. A singleton object is usually used as a carrier for storing configuration information in a program, because it guarantees that other objects will read consistent information. For example, in a server program, the configuration information for the server may be stored in a database or file, which is read uniformly by a single object, and other objects in the service process can access the singleton object if they want to obtain the configuration information. This approach greatly simplifies configuration management in complex environments, especially in multi-threaded environments, but it can also lead to some synchronization problems as the application scenario differs. several ways of writing: the first type (lazy, thread insecure):

public class Singleton {
private static Singleton instace;
Private Singleton () {}
public static Singleton Getinstace () {
if (instace = = null) {
Instace = new Singleton ();
}
return instace;
}
This is the simplest implementation, which writes the constructor of the class to private so that other classes cannot instantiate the class, and then provides a static instance in the class and can be returned to the consumer. This allows the user to use this reference to an instance of the class. Cons: This type of lazy loading is obvious, but the fatal is that the multithreading does not work properly. the second type (lazy, thread safe):

public class Singleton {
private static Singleton instace;
Private Singleton () {}
public static synchronized Singleton Getinstace () {
if (instace = = null) {
Instace = new Singleton ();
}
return instace;
}
The workaround is also simple: lock-in, one thread must wait for another thread to be created before using this method, which guarantees the uniqueness of the Singleton.
Cons: Inefficient, and in most cases no synchronization is required.
The third type (a Hungry man):

public class Singleton {
private static Singleton instance = new Singleton ();
Private Singleton () {}
public static Singleton getinstance () {
return instance;
}
} or

public class Singleton {
private static Singleton instace;
static{
Instace = new Singleton ();
}
Private Singleton () {}
public static Singleton Getinstace () {
return instace;
}
} Advantages and Disadvantages: This approach is based on the classloder mechanism to avoid multithreading synchronization problem, however, instance in class loading is instantiated, although there are many reasons for class loading, most of the singleton mode is called GetInstance method, However, it is not certain that there are other ways (or other static methods) that cause the class to load, when initializing instance obviously does not achieve the effect of lazy loading. The fourth type (static inner Class):

public class Singleton {
private Static Class singletonclassinstance{
private static final Singleton instace = new Singleton ();
}
Private Singleton () {}
public static final Singleton Getinstace () {
return singletonclassinstance.instace;
}
This approach also takes advantage of the classloder mechanism to ensure that there is only one thread when initializing instance, and it differs from the third, as follows: The third: As long as the Singleton class is loaded, the instance is instantiated (not reaching the lazy Loading effect). The fourth type: The Singleton class is loaded, instance is not necessarily initialized because: Singletonclass has no static properties, the class is not actively used and is not initialized. Until getinstance () is called, the Singletonclassinstance class is loaded first, and the class has a static Singletonclass instance, so you need to call Singletonclass's construction method. Then getinstance () will return the instance of this inner class to the user. Since this instance is static, it is not constructed more than once.
Scenario: If instantiating instance is draining resources, I want him to delay loading, on the other hand, I don't want to instantiate when the Singleton class loads. is more appropriate than the third. Fifth type (double check lock): for the second type of lock mode optimization. The second is that the entire method must be locked to optimize performance by separating the operation that detects null from the operation that created the object.

Public class Singleton {
Private volatile static Singleton instance;
Private Singleton () {}
public static Singleton Getinstace () {
if (instance = = null)
{
Synchronized (Si Ngleton.class) {
if (instance = = = null) {
Instance = new Singleton ();
}
}
}
return instance;
} The
} is about volatile because of the following reasons: What steps are required to create a variable? One is to apply a piece of memory, call the constructor to initialize the operation, and the other is to assign a pointer to this block of memory. The JVM does not have a prescribed order, both of which are placed behind because of compiler optimizations that might invoke the constructor method. So use volatile to guarantee the order of execution. Summary ******************* Actual or recommended fourth, static internal class to implement a singleton mode. and the static string of our previous notes. Related knowledge is delayed loading, lock synchronization and optimization, static internal classes and so on. Of course, the design pattern of 23 kinds of many, I am still learning, to do ingenious to keep trying, not bound by the rules.
Reference: http://cantellow.iteye.com/blog/838473 http://devbean.blog.51cto.com/448512/203501/

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.