volatile修饰变量(而synchronized修饰方法或一段代码),保证各线程访问的均是main memory中的变量而非线程memory中的一份cache。
public class Singleton {
private volatile static Singleton anInstance;
private Singleton() {}
public static Singleton getInstance() { //若此处就用synchronized则每次getInstance的代价都非常高
if( anInstance == NULL ){ //可能多个线程第一次均同时满足此条件
synchronized ( Singleton.class ) { //此时才进行代价较高的synchronized
if( anInstance == NULL ) {
anInstance = new Singleton();
}
}
}
return anInstance;
}
}