Java Reference
In-Depth Information
LAZY INITIALIZATION RUNTIME PERFORMANCE
The usual performance penalty for checking whether lazily initialized variables have been initial-
ized may not always exist. Consider this example from the JDK's ArrayList class. That class
maintains an array of the elements it stores, and prior to JDK 7u40, pseudocode for the class
looked like this:
public
public class
class ArrayList
ArrayList {
private
private Object [] elementData = new
new Object [ 16 ];
int
int index = 0 ;
public
public void
void add ( Object o ) {
ensureCapacity ();
elementData [ index ++] = o ;
}
private
private void
void ensureCapacity () {
iif ( index == elementData . length ) {
... reallocate array and copy old data in ...
}
}
}
In JDK 7u40, this class was changed so that the elementData array is initialized lazily. But be-
cause the ensureCapacity() method already needed to check the array size, the common meth-
ods of the class didn't suffer a performance penalty: the code to check for initialization is the
same as the code to check whether the array size needs to be increased. The new code uses a stat-
ic, shared, 0-length array so that performance is the same:
public
public class
class ArrayList
ArrayList {
private
private static
static final
final Object [] EMPTY_ELEMENTDATA = {} ;
private
private Object [] elementData = EMPTY_ELEMENTDATA ;
}
That means the ensureCapacity() method can be (essentially) unchanged, since the index and
elementData.length will both start at 0.
When the code involved must be thread-safe, lazy initialization becomes more complicated.
As a first step, it is easiest simply to add traditional synchronization:
public
public class
class CalDateInitialization
CalDateInitialization {
private
private Calendar calendar ;
private
private DateFormat df ;
Search WWH ::




Custom Search