Java Reference
In-Depth Information
private
private synchronized
void report ( Writer w ) {
iif ( calendar == null
synchronized void
null ) {
calendar = Calendar . getInstance ();
df = DateFormat . getDateInstance ();
}
w . write ( "On " + df . format ( calendar . getTime ()) + ": " + this
this );
}
}
Introducing synchronization into the solution opens up the possibility that the synchroniza-
tion will become a performance bottleneck. That case should be rare. The performance bene-
fit from lazy initialization only occurs when the object in question will only rarely initialize
those fields—since if it usually initializes those fields, then no memory has actually been
saved. So synchronization becomes a bottleneck for lazily initialized fields when an infre-
quently used code path is suddenly subject to use by a lot of threads simultaneously. That
case is not inconceivable, but it isn't the most common case either.
Solving that synchronization bottleneck can only happen if the lazily initialized variables are
themselves thread-safe. DateFormat objects are not thread-safe, so in the current example, it
doesn't really matter if the lock includes the Calendar object: if the lazily initialized objects
are suddenly used heavily, the required synchronization around the DateFormat object will
be an issue no matter what. The thread-safe code would have to look like this:
public
public class
class CalDateInitialization
CalDateInitialization {
private
private Calendar calendar ;
private
private DateFormat df ;
private
private void
void report ( Writer w ) {
unsychronizedCalendarInit ();
synchronized
synchronized ( df ) {
w . write ( "On " + df . format ( calendar . getTime ()) + ": " + this
this );
}
}
}
Lazy initialization that involves an instance variable that is not thread-safe can always syn-
chronize around that variable (e.g., using the synchronized version of the method shown
previously).
Search WWH ::




Custom Search