Design mode 1----Singleton (single State) __ design mode

Source: Internet
Author: User
Tags volatile

Single-state definition: The main purpose of Singleton mode is to ensure that only one instance of a class in a Java application exists.

A single case pattern has some features:
1, Singleton class can only have one instance.
2. A singleton class must create its own unique instance itself.
3. A singleton class must provide this instance to all other objects.
The singleton pattern ensures that a class has only one instance and instantiates it itself and supplies the instance to the entire system.

Simplest mode (a hungry man):

Privatize a class constructor so that other classes cannot instantiate the class, and then provide a static instance in the class and return it to the consumer

Class singleton{

private static Singleton uniqueinstance = new Singleton ();

Private Singleton () {}
public static Singleton getinstance () {
return uniqueinstance; }

}

Lazy Load:

Class singleton{
private static Singleton Uniquesingleton;
Private Singleton () {}
public static Singleton getinstance () {

if (Uniquesingleton = = null) {
Uniquesingleton =new Singleton ();
}
return Uniquesingleton;
}
}

Lazy loading mode is used, but there is a fatal problem. When multiple threads call getinstance () in parallel, multiple instances are created. In other words, it does not work under multithreading. The easiest way to solve the problem above is to set the entire getinstance () method to sync (synchronized)

Public staticsynchronized Singleton getinstance () {
if (Uniquesingleton = = null) {
Uniquesingleton =new Singleton (); }
return Uniquesingleton;
}

Although it is thread-safe and solves multiple-instance problems, it is not efficient. Because only one thread can call the GetInstance () method at any time. However, the synchronization operation is only required on the first call, that is, the first time a singleton instance object is created

Double-check lock mode (double checked locking pattern) is a method of using synchronized blocks to lock. Because there will be two checks uniquesingleton==null, once in the synchronized block, once in the synchronized block. Why do I have to check again in the sync block? Because there may be more than one thread going into the sync block together, multiple instances will be generated if no two tests are performed within the synchronization block.

public static Singleton getinstance () {
if (Uniquesingleton = = null) {
Synchronized (Singleton.class) {
if (Uniquesingleton = = null) {
Uniquesingleton =new Singleton ();
}
}
}
return Uniquesingleton;
}

Uniquesingleton =new Singleton (); This is not an atomic operation, in fact in the JVM this sentence probably did the following 3 things.

1. For Uniquesingleton distribution,

2. Invoke the Singleton constructor to initialize the member variable.

3. Point the Uniquesingleton object to the allocated memory space (Uniquesingleton is not null after this step)

However, there is an optimization of instruction reordering in the JVM's Just-in-time compiler. In other words, the order of the second and third steps above is not guaranteed, and the final order of execution may be 1-2-3 or 1-3-2. If it is the latter, then the 3 execution, 2 is not executed before the thread two preemption, then Uniquesingleton has been non-null (but not initialized), so thread two will return directly to Uniquesingleton, and then use, and then logically to the error.

We just need to declare the Uniquesingleton variable as volatile. Privatevolatilestatic Singleton uniqueinstance;

The main reason for using volatile is another feature: banning command reordering optimizations. That is, there is a memory barrier (on the generated assembler code) behind the assignment operation of the volatile variable, and the read operation is not reordered before the memory barrier. For example, the above example, the fetch operation must be done after 1-2-3 or after the 1-3-2, there is no execution to 1-3 and then fetch the value of the case. From the point of view of "first occurrence principle", it is that the write operation for a volatile variable occurs first in the face of the variable reading ("Back" is the order of time).

However, it is also problematic to pay special attention to the use of volatile dual-check locks in previous versions of Java 5. The reason is that the previous Java 5 JMM (Java memory model) is flawed, the immediate declaration of variables into volatile can not completely avoid reordering, mainly volatile variables before and after the code still has a reordering problem. This volatile screen reordering problem is fixed in Java 5, so you can safely use volatile after that. Methods of using static inner classes

public class Singleton {

private Static Class Singletonholder {
private static final Singleton INSTANCE = new Singleton ();
}     

Private Singleton () {

    }     

public static final Singleton getinstance () {
return singletonholder.instance;
}

}

Thread-safety issues are ensured with the JVM's own mechanism; because Singletonholder is private, there is no way to access it except for getinstance (), so it is lazy; there is no synchronization when reading the instance, no performance flaws, and no dependencies on the JDK version



Recommended Reference Articles:

Bewitched into:http://www.cnblogs.com/whgw/archive/2011/10/05/2199535.html

Sunnylocus: http://sunnylocus.iteye.com/blog/228419

by wuchong:http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/(well worth looking at)


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.