我在处理高并发单例类的单元测试时,遇到了以下奇怪的行为(在JDK 1.8.0_162上进行测试):
private static class SingletonClass {
static final SingletonClass INSTANCE = new SingletonClass(0);
final int value;
static SingletonClass getInstance() {
return INSTANCE;
}
SingletonClass(int value) {
this.value = value;
}
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
System.out.println(SingletonClass.getInstance().value); // 0
// Change the instance to a new one with value 1
setSingletonInstance(new SingletonClass(1));
System.out.println(SingletonClass.getInstance().value); // 1
// Call getInstance() enough times to trigger JIT optimizations
for(int i=0;i<100_000;++i){
SingletonClass.getInstance();
}
System.out.println(SingletonClass.getInstance().value); // 1
setSingletonInstance(new SingletonClass(2));
System.out.println(SingletonClass.INSTANCE.value); // 2
System.out.println(SingletonClass.getInstance().value); // 1 (2 expected)
}
private static void setSingletonInstance(SingletonClass newInstance) throws NoSuchFieldException, IllegalAccessException {
// Get the INSTANCE field and make it accessible
Field field = SingletonClass.class.getDeclaredField("INSTANCE");
field.setAccessible(true);
// Remove the final modifier
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
// Set new value
field.set(null, newInstance);
}
主方法的最后两行对INSTANCE的值持不同意见-我猜测JIT已完全摆脱了该方法,因为该字段是静态final的。 移除final关键字使代码输出正确的值。
抛开你对单例模式的同情(或缺乏同情),暂且忘记使用反射可能会遇到麻烦 - 我的假设是否正确,即JIT优化应该受到责备? 如果是这样-这些局限于静态final字段吗?
static final
字段的类。除此之外,这个反射hack是否由于JIT或并发而中断并不重要。 - Holger