CHAPTER 11
CONCURRENCY
334
Both of these idioms (
normal initialization
and
lazy initialization with a
synchronized accessor
) are unchanged when applied to static fields, except that
you
add the
static
modifier to the field and accessor declarations.
If you need to use lazy initialization for performance on a static field, use
the
lazy initialization holder class idiom
.
This idiom exploits the guarantee that a
class will not be initialized until it is used [JLS, 12.4.1]. Here’s how it looks:
// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
private static FieldType getField() { return FieldHolder.field; }
When
getField
is
invoked for the first time, it reads
FieldHolder.field
for
the first time, causing the initialization of the
FieldHolder
class. The beauty of
this idiom is that the
getField
method is not synchronized and performs only a
field access, so lazy initialization adds practically nothing to the cost of access. A
typical VM will synchronize field access only to initialize the class.
Once the class
is initialized, the VM patches the code so that subsequent access to the field does
not involve any testing or synchronization.
Do'stlaringiz bilan baham: