Java Reference
In-Depth Information
Consider a somewhat different example, where a large ConcurrentHashMap is lazily initial-
ized:
public
public class
class CHMInitialization
CHMInitialization {
private
private ConcurrentHashMap chm ;
public
public void
void doOperation () {
synchronized
synchronized ( this
this ) {
iif ( chm == null
null ) {
chm = new
new ConcurrentHashMap ();
... code to populate the map ...
}
}
... use the chm ...
}
}
Because the ConcurrentHashMap can be safely accessed by multiple threads, the extra syn-
chronization in this example is one of the infrequent cases where properly used lazy initializ-
ation could introduce a synchronization bottleneck. (Such a bottleneck should still be rare,
though; if access to the hashmap is that frequent, consider if anything is really saved by ini-
tializing it lazily.) The bottleneck is solved using the double-checked locking idiom:
public
public class
class CHMInitialization
CHMInitialization {
private
private volatile
volatile ConcurrentHashMap instanceChm ;
public
public void
void doOperation () {
ConcurrentHashMap chm = instanceChm ;
iif ( chm == null
null ) {
synchronized
synchronized ( this
this ) {
chm = instanceChm ;
iif ( chm == null
null ) {
chm = new
new ConcurrentHashMap ();
... code to populate the map
instanceChm = chm ;
}
}
... use the chm ...
}
}
}
Search WWH ::




Custom Search