java语句顺序有时非常重要

我们学习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还没有初始化。这是因为进行类载入时。静成变量的初始化顺序造成的。

原文地址:https://www.cnblogs.com/tlnshuju/p/7134212.html