关于Java中Integer所涉及的缓冲区的理解
标签: Java Integer
2+2竟然等于5?
public class AA {
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);
newCache[132] = newCache[133];
int a = 2;
int b = a + a;
System.out.printf("%d+%d=%d", a, a, b);//结果为:2+2=5
}
}
上面用到了反射机制的相关知识,所以一开始我觉得结果肯定有蹊跷,不一定等于4,但怎么也不会想到结果竟然为5。为了搞清楚这是怎么回事,我们先看下面的这个Integer的缓冲区的知识。
Integer的缓冲区
public class A {
public static void main(String[] args) {
Integer a = 128, b = 128;
System.out.println(a == b);//false
Integer c = 127, d = 127;
System.out.println(c == d);//true
}
}
上面的运行结果一运行吓一跳,明明按照基本的java知识,两个结果都应该为false啊,怎么会一个false一个true呢,我们在看下面的一个例子:
public class C {
public static void main(String[] args) {
Integer a = new Integer(128);
Integer b = new Integer(128);
System.out.println(a == b);//false
Integer c = new Integer(127);
Integer d = new Integer(127);
System.out.println(c == d);//false
}
}
这个运行结果是符合我们所知道的java基本知识的,即new操作的每一个对象的指向堆中不同的内存区域,所以运行结果都为false。看到这我们觉得很奇怪的同时,肯定也想到了这种现象是因为Integer的自动装箱声明对象并初始化时在底层调用了什么方法或者存在其他的机制造成的吗?通过查阅源码以及相关资料,这就是因为Integer中的缓冲区机制造成的。
1.缓冲区的源代码如下:
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) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
2.自动装箱调用的方法的源代码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
结合上面两段Integer的源代码,我们就可以明白Integer缓冲区是怎么回事,也会明白上面的运行结果采用自动装箱的方式时a==b为false,而c==d为true。下面是对上面两段代码的大概解读:
我们可以只看第二段代码和第一段代码的1 4 25 26 28这五行,其实Integer类
中封装了一个私有的静态内部类IntegerCache
,该类中又定义了一个Integer cache[]
的缓冲区,大小其实就是区间[-128, 127]
的大小,该区间内的数已经通过实例化操作将各自对应的Integer对象封装在了数组cache
中,即Integer cache[0] = new Integer(-128);
依次初始化到数字127结束。
那么在自动装箱操作时,比如Integer a = 128;
因为128不在区间[-128, 127]
中,所以Integer的valueOf方法就会return new Integer(128),所以相当于Integer a = new Integer(128);
类似得Integer b = 128;
也相当于Integer b = new Integer(128);
所以a==b的结果为false。
但是当声明对象的值在区间[-128, 127]
中时,Integer的valueOf方法就会return cache[缓冲区]中的Integer对象,所以Integer c = 127;和Integer d = 127;
的对象c、d的就相当于c=d=cache[255],
即对象c和d的指向是相同的,故c==d结果为true。归根究底,就是Integer内部缓冲区造成的,同时我们也知道了Integer的自动装箱操作并仅仅是简化了书写,将 new Integer(i)单纯的省略掉。
为什么会在Integer中对区间[-128, 127]的数加入缓冲区机制呢?
主要就是因为区间内的数在平时是最常用的,多次使用相同的底层对象可以有助于提高内存的优化,这一点在编程时也可以借鉴。
通过上面的论述,现在我们在回头看2+2=5的问题!
public class AA {
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);
newCache[132] = newCache[133];
int a = 2;
int b = a + a;
System.out.printf("%d+%d=%d", a, a, b);//结果为:2+2=5
}
}
首先,我们需要知道System.out.printf("%d+%d=%d", a, a, b);
这句代码是执行时是这样的,System.out.printf("%d+%d=%d",new Object[]{Integer.valueOf(a),Integer.valueOf(a),Integer.valueOf(b)});
(反编译就可以看到这个效果!!)惊奇地发现原来printf的打印方法
底层是调用了Integer.valueOf方法
对数字进行打印输出的,那么在区间[-128, 127]的数肯定会用到Integer的缓冲区了。
然后我们再看代码中第9行的newCache[132] = newCache[133];
一下子也就就明白了上述代码通过反射机制修改了Integer缓冲区中数字4所对应的Integer对象的指向。即Integer newCache[132] = new Integer(4)
,Integer newCache[133] = new Integer(5)
执行 newCache[132] = newCache[133]
后,对象newCache[132]所对应的值为5,所以上面通过printf打印后,2+2=5 ,如果没有反射机制修改cache缓冲区的话,2+2=4,代码如下:
public class AA {
public static void main(String[] args) throws NoSuchFieldException,IllegalAccessException {
int aa = 2;
int bb = aa + aa;
System.out.println(aa+"+"+aa+"="+bb);
//结果为:2+2=4
System.out.printf("%d+%d=%d", aa, aa, bb);
//结果为:2+2=4
}
}
补充:println方法打印用的是String.valueOf(i)方法,将其装化为字符串打印的,而printf用的是Integer.valueOf(i)方法,从而用到了Integer的缓冲区机制,二者略微不同。
下面的代码答案是多少呢?
public class B {
public static void main(String[] args) {
Integer a = Integer.valueOf(128);
Integer b = Integer.valueOf(128);
System.out.println(a == b);//false
Integer c = Integer.valueOf(127);
Integer d = Integer.valueOf(127);
System.out.println(c == d);//true
Integer e = 127;
Integer f = 128;
System.out.println(e==c);//true,缓冲区内的相同对象,所以肯定是true
System.out.println(f==c);//false
System.out.println(f==a);//false
}
}