Java Reference
In-Depth Information
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 ...
}
The volatile keyword accomplishes two things in this example. First, note that the hashmap is
initialized using a local variable first, and only the final (fully initialized) value is assigned to the
instanceChm variable. If the code populating the hashmap were using the instance variable direc-
tly, a second thread could see a partially populated map. And second, it ensures that when the map
is completely initialized, other threads will immediately see that value stored into the in-
stanceChm variable.
The purpose of synchronization is to protect access to values in memory—that is, to vari-
ables. As discussed in Chapter 4 , variables may be temporarily stored in registers, which is
much more efficient than directly accessing them in main memory. Register values are not
visible to other threads; the thread that modifies a value in a register must at some point flush
that register to main memory so that other threads can see the value. The point when the re-
gister values must be flushed is dictated by thread synchronization.
The actual semantics can get fairly complicated, but the easiest way to think of this is that
when a thread leaves a synchronized block, it must flush any modified variables to main
memory. That means other threads that enter the synchronized block will see the most re-
cently updated values. Similarly, CAS-based protection ensures that variables modified dur-
ing their operation are flushed to main memory, and a variable marked volatile is always
consistently updated in main memory whenever it is changed.
In Chapter 1 , I mentioned that you should learn to avoid nonperformant code constructs in
Java, even if it seems like that might be “prematurely optimizing” your code (it isn't). An in-
teresting case of that—and a real-world example—comes from this loop:
Search WWH ::




Custom Search