Java Reference
In-Depth Information
USES OF VOLATILE IN EXAMPLES
The Java Memory Model has subtly influenced two other examples in this topic. Chapter 2 dis-
cussed the problems in writing a microbenchmark; the ultimate solution there required a volat-
ile variable to store the result of each loop iteration:
public
public class
class MicroBenchmark
MicroBenchmark {
private
private volatile
volatile double
double answer ;
public
public static
static void
void main ( String [] args ) {
long
long then = System . currentTimeMills ();
for
for ( int
int i = 0 ; i < nLoops ; i ++) {
answer = compute ( randomValue [ i ]);
}
long
long now = System . currentTimeMills ();
System . out . println ( "Elapsed time: " + ( now - then ));
}
}
As the compiler optimized the code, it could unroll the loop, yielding the following pseudocode:
for
for ( int
int i = 0 ; i < nLoops ; i += 4 ) {
answer = compute ( randomValue [ i ]);
answer = compute ( randomValue [ i + 1 ]);
answer = compute ( randomValue [ i + 2 ]);
answer = compute ( randomValue [ i + 3 ]);
}
If the JVM stored the value of answer in a register, it could notice that the register is written mul-
tiple times without being read (since other threads cannot read the register), and as a result optim-
ize away all the loop calculations except for the final one. Defining answer as volatile ensures
that the JVM must store the calculation of each loop as it is made. The JVM cannot optimize
those calculations out, since it can never know if another thread will come along and read the
value out of main memory.
Similarly, the double-checked locking example in Chapter 7 required the use of a volatile vari-
able:
private
private volatile
volatile ConcurrentHashMap instanceChm ;
...
public
public void
void doOperation () {
ConcurrentHashMap chm = instanceChm ;
Search WWH ::




Custom Search