关于Integer.IntegerCache
先来看一个小示例:
public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException{
Integer a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 100, d = 100;
System.out.println(c == d);
}
// 输出结果如下:
false
true
那么为什么会这样呢?
我们知道 == 在java语言中,用作比较两个引用是否引用同一个对象,如果是则为true,反之为false。由此可见,上例中,a跟b为不同对象,c和d应该是同一个对象。那么究竟为什么c跟d会引用同一个对象呢?
原因在于在Integer中对常用区间内的整数[-128 ~ 127]进行了缓存处理,在Integer字节码被虚拟机加载时就会创建一个静态的Integer数组缓存这些常用的Integer对象。Integer中内部类IntegerCache源码如下:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax=<size> option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
下面在看一个有趣的例子,我们利用反射,去修改一下这个IntegerCache数组的内容:
public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException{
Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
System.out.println("缓存起始于:" + newCache[0]);
System.out.println("缓存截止于:" + newCache[newCache.length-1]);
newCache[132] = newCache[133];
int a = 2;
int b = a+ a;
System.out.printf("%d + %d = %d", a, a, b);
}
// 输出结果如下:
缓存起始于:-128
缓存截止于:127
2 + 2 = 5
我们修改了这个数组的缓存值,因此得到了一个错误的运算结果!