一个简单的面试题
public static void main(String[] args) { Integer in1 = 100; Integer in2 = 100; Integer in3 = 200; Integer in4 = 200; System.out.println(in1 == in2); System.out.println(in3 == in4); }
运行结果:
true false
你答对了吗?
从自动装箱谈Integer缓存
上述面试题中,in1,in2,in3,in4四个Integer对象都是通过直接赋值int变量完成初始化的,这种赋值方式我们成为自动装箱。
实际上,自动装箱功能只是Java编译器自动帮我们完成了调用Integer.valueOf(int i)的过程,也就是说:
Integer in1 = 100;<-等价于->Integer in1 = Integer.valueOf(100);
了解了这个道理,我们再来回想上面这个问题:为什么一样的调用valueOf方法,却得不到一样的值?
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
我们看到,在jdk1.5中,加入了valueOf的这个实现过程。在if条件中,如果 i 的值在[IntegerCache.low , IntegerCache.high]之间的话,则取IntegerCache.cache中的一个元素。
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 {@code -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) { 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() {} }
缓存类在第一次使用Integer类时被初始化。通过一个for循环初始化了一个拥有256个Integer对象的数组供开发人员使用。它们的范围默认是[-128 , 127],127可以通过修改JVM启动参数-XX:AutoBoxCacheMax=size进行调整。这种方式通过使用相同的对象引用来实现缓存和复用,以此来节省内存和提高性能。
再谈==和equals()
双等于==比较的是对象的内存地址,对于-128到127之间的整数,只要这个引用是通过自动装箱或者显式valueOf()指向一个Integer对象,那么它一定会指向一个IntegerCache.cache数组中的对象,因此物理地址一定相等,而在这个区间以外的整数,因为没有缓存的原因,需要通过new Integer()的方式开辟一块新的物理地址来存储这个对象,因此物理地址一定不同。所以才会有前面面试题中的结果。
Integer.equals()方法,提供了比较两个Integer对象的方法,所以不管是通过new 还是 valueOf方式创建的Integer对象,在实际的业务需求中,往往都是需要比较对象中存储的整数值而不是物理地址,所以,为了避免混淆,应当都使用equals方式来比较两个Integer对象,这样可以减少很多问题。
总结
代码应当是服务于业务的,而不是面试题。这种==比较两个Integer对象的方式应该仅仅在面试题中出现,而不应该是在业务实现中出现,虽然某些时候,可以实现一样的效果,但是代码应该不仅能够实现逻辑的正确性,也应该能够表达一种正确的语义,使他人在阅读你的代码时能够清楚的明白这行代码所要表达的含义。
但并不是说我们不需要理解它的实现过程和需要注意的问题,这道面试题虽然可能不会真正的运用到实际的业务实现中去,但是却提供了一种帮助我们深入了解jdk的手段,使我们更好的了解到API开发人员在帮助我们解决什么问题。所以,不论是工作还是学习,都应该认清我们的需要。
综上,就是对Integer对象缓存策略的剖析和感想,如有疑问,欢迎文末留言。
---欢迎关注【Java圣斗士】,我是你们的小可爱(?ω?) Morty---
---专注IT职场经验、IT技术分享的灵魂写手---
---每天带你领略IT的魅力---
---期待与您陪伴!---