I am trying to fix double checked locking with Bloch's effective java recommendation. But a small variation in my code is that the field type is static and the method to create the field type is instance method. Will the below variation for creating a static field work?
private static volatile FieldType field4;
// NOTE: The code for this method in the first printing had a serious error (see errata for details)!
public FieldType getField4() {
FieldType result = field4;
if (result != null) // First check (no locking)
return result;
synchronized(Initialization.class) {
if (field4 == null) // Second check (with locking)
field4 = computeFieldValue();
return field4;
}
}
I cannot make the method static method to // Lazy initialization holder class idiom for static fields - Page 334.
Assuming you are using Java 5 or later1, the above code is thread-safe2.
It doesn't matter that either the method or field is static
provided that:
volatile
and,The former is obviously true. The latter is true because all calls to getField4()
are locking the same Class
object.
1 - Prior to Java 5, the specified semantics of volatile
are not sufficient to guarantee that the code is thread-safe.
2 - Thread-safe but ugly. It is better to avoid the DCL idiom and use one of the other alternatives.
I cannot make the method static method ...
I don't see why not. It is private
so you should not be constrained as to whether it is a static or instance method. It should only affect the current class.
But as noted above, it doesn't make any difference to the idiom.