From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:
public class Singleton {
Declaring the variable as volatile
guarantees that all accesses to it actually read its current value from memory.
Without volatile
, the compiler may optimize away the memory accesses to the variable (such as keeping its value in a register), so only the first use of the variable reads the actual memory location holding the variable. This is a problem if the variable is modified by another thread between the first and second access; the first thread has only a copy of the first (pre-modified) value, so the second if
statement tests a stale copy of the variable's value.