The double check mode is mentioned in article 48th of the Effecitve Java book, and it is pointed out that this pattern is not normally applicable in Java. The structure of the pattern is as follows:
Public Resource getresource () {
if (Resource = null) {
synchronized (this) {
if (resource==null)
{ Resource = new resource ();
}} return resource;
}
The pattern is improved on the following code:
Public synchronized Resource GetResource () {
if (Resource = = null) {
Resource = new Resource ();
}
return resource;
The purpose of this code is to initialize the resource delay. But every time you visit it, you need to sync. In order to reduce the cost of synchronization, there is a double check mode.
The reason for double check mode in Java is invalid is that the reference type is not thread safe in the case of a different step. Double check mode is applicable for basic types except long and double. For example, the following code is correct:
private int count;
public int GetCount () {
if (count = = 0) {
synchronized (this) {
if (count = = 0) {
count = Computecount (); A time-consuming calculation
}}
return
count;
}
The above is a general conclusion about the double check mode (double-check idiom) in Java. But it's not over yet, because the Java memory model is also improving. Doug Lea wrote in his article: "Based on the latest JSR133 Java memory model, if you declare a reference type as volatile, the double check mode works." So in the future to use the double check mode in Java, you can use the following code:
private volatile Resource Resource;
Public Resource getresource () {
if (Resource = null) {
synchronized (this) {
if (resource==null)
{ Resource = new resource ();
}} return resource;
}
Of course, it has to be in the Java that follows the JSR133 specification.
As a result, double-check is not available when J2SE 1.4 or earlier in the multithreaded or JVM tuning due to Out-of-order writes. This problem has been fixed in J2SE 5.0, and you can use the volatile keyword to guarantee a single example under multithreading.
public class Singleton {
private volatile Singleton instance = null;
Public Singleton getinstance () {
if (instance = null) {
synchronized (this) {
if (instance = null) {
Inst ance = new Singleton ();
}} return instance;
}
The recommended method is initialization on Demand Holder (Iodh),
public class Singleton {
static class Singletonholder {
static Singleton instance = new Singleton ();
} Public
static Singleton getinstance () {return
singletonholder.instance;
}
}
The above is the entire content of this article, I hope to learn Java program to help you.