The double check mode is mentioned in Article 48th in the book "Keep Itve Java", and it is pointed out that this mode is generally not applicable in Java. The structure of this mode is as follows: private resource;
Public resource getresource ()...{
If (resource = NULL )...{
Synchronized (this )...{
If (resource = NULL )...{
Resource = new resource ();
}
}
} Return resource;
}
This mode improves the following code: Public synchronized resource getresource ()...{
If (resource = NULL )...{
Resource = new resource ();
}
Return resource;
}
The purpose of this Code is to delay Resource Initialization. However, synchronization is required for each access. To reduce synchronization overhead, a dual check mode is available.
In Java, the reason why the double check mode is invalid is that the reference type is not thread-safe without synchronization. In addition to the basic types of long and double, the double check mode is applicable. For example, the following code is correct:
Private int count;
Public int getcount ()...{
If (COUNT = 0 )...{
Synchronized (this )...{
If (COUNT = 0 )...{
Count = computecount (); // time-consuming computing
}
}
} Return count;
}
The above is the general conclusion about the double-check idiom in Java. But it is not over yet, because the memory mode of Java is also being improved. Doug Lea wrote in his article: "If you declare the reference type as volatile based on the latest jsrloud Java memory model, the dual-Check Mode will work." See http://gee.cs.oswego.edu/dl/cpj/updates.html.
Therefore, to use the Double Check Mode in Java in the future, you can use the following code:
Private volatile resource;
Public resource getresource ()......{
If (resource = NULL )......{
Synchronized (this )......{
If (resource = NULL )......{
Resource = new resource ();
}
}
} Return resource;
}
Of course, it must be in Java that complies with the jsr133 specification.