我们学习java时,通常被告知,变量定义的顺序不重要,但是以下程序确在jdk 1.7上运行出错。
public class FactoryImpl implements Serializable {
private final static FactoryImpl INSTANCE = new FactoryImpl();
private final static AtomicInteger count = new AtomicInteger(0);
private int id;
private FactoryImpl() {
id = count.incrementAndGet();
}
public int getId() {
return id;
}
public static FactoryImpl getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
FactoryImpl impl1 = FactoryImpl.getInstance();
System.out.println(impl1.id);
}
}
把以下代码调整顺序之后可以执行成功。
private static final FactoryImpl INSTANCE = new FactoryImpl();
private final static AtomicInteger count = new AtomicInteger(0);
原因如下,如果不调整时,当类被加载时,先初始化INSTANCE静态变量,这时,会调用FactoryImpl构造方法,在此构造方法里,调用count.incremnetAndGet();这时count还没有初始化。这是由于进行类加载时,静成变量的初始化顺序造成的。