Four methods and some features of Java implementation of single case pattern _java

Source: Internet
Author: User

First, a hungry man type single case class

Copy Code code as follows:

public class Singleton
{
Private Singleton () {

}

private static Singleton instance = new Singleton ();

private static Singleton getinstance () {
return instance;
}
}

Features: A hungry man-type advance instantiation, no lazy multithreaded problem, but whether we call getinstance () there will be an instance in memory

Second, the internal class type single case class

Copy Code code as follows:

public class Singleton
{
Private Singleton () {

}

Private Class Singletonholedr () {
private static Singleton instance = new Singleton ();
}

private static Singleton getinstance () {
return singletonholedr.instance;
}
}

Features: In the inner class, the delay loading is implemented, only when we call getinstance () will we create a unique instance into memory. And it solves the problem of multithreading in the lazy. The solution is to take advantage of the characteristics of the ClassLoader.

Three, the lazy type single case class

Copy Code code as follows:

public class Singleton
{
Private Singleton () {

}

private static Singleton instance;
public static Singleton getinstance () {
if (instance = = null) {
return instance = new Singleton ();
}else{
return instance;
}
}
}

Features: In the lazy type, threads A and B, when thread a runs to line 8th, jumps to thread B, and when B runs to 8 rows, the instance of two threads is empty, which generates two instances. The solution is to sync:

can be synchronized but not efficient:

Copy Code code as follows:

public class Singleton
{
Private Singleton () {

}

private static Singleton instance;
public static synchronized Singleton getinstance () {
if (instance = = null) {
return instance = new Singleton ();
}else{
return instance;
}
}
}

This does not make a mistake, because the whole getinstance is a whole "critical section", but it is inefficient, because our goal is actually to first initialize the instance need locking (lock), When you take a instance, you don't need to sync at all.

So the wise people came up with the following approach:

Double check lock writing:

Copy Code code as follows:

public class singleton{
private static Singleton single; Declaring a variable of a static Single Instance object
Private Singleton () {}//proprietary constructor method

public static Singleton Getsingle () {//external can get objects through this method
if (single = null) {
Synchronized (Singleton.class) {//guaranteed that only one object can access this synchronization block at the same time
if (single = null) {
Single = new Singleton ();
}
}
}
return single; Returns the Created object
}
}

The simple idea is that we just need to sync (synchronize) the part of the code that initializes the instance so that the code is both correct and efficient.
This is called the "double check lock" mechanism (as the name suggests).
Unfortunately, this kind of writing is wrong on many platforms and optimizing compilers.

The reason: instance = new Singleton () The behavior of this line of code on different compilers is unpredictable. An optimization compiler can be legitimately implemented as follows instance = new Singleton ():

1. Instance = Allocate memory to the new entity

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

Now imagine that threads A and b are called getinstance, thread A enters first, and is kicked out of the CPU when it executes to step 1. Then thread B enters, and b sees that instance is not NULL (memory has been allocated), so it begins to use instance with ease, but this is wrong, because at this moment, the instance member variable is also the default value, A has not had time to perform the steps and second completes the initialization of the instance.

Of course, the compiler can do the same:

1. temp = Allocate memory

2. Call the Temp constructor

3. Instance = Temp

If the compiler behaves like this we seem to have no problem, but the fact is not so simple, because we do not know what a compiler specifically does, because in the Java memory model does not define this problem.

Double check locks apply to the underlying type (for example, int). Obviously, because the underlying type does not call the constructor this step.

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.