关于 Integer 缓存池中的 IntegerCache
以下摘自源码:
Oracle OpenJDK version 1.8.0_331
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= 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.
可总结为:
- 在程序第一次创建 Integer 对象时会初始化一个 cache
 - 这个 cache 会对 -128 到 127 进行自动装箱
 - 可由 
-XX:AutoBoxCacheMax=修改 cache 的大小 
具体实现:
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
     	// 静态初始化块, 确保在仅在第一次创建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);   // 如果手动把上限值调到127以下, 依然会取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;
            // 在这里缓存Integer对象
            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() {}
    }
测试:
public class test {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        System.out.println(a == b);  // true
        Integer c = 128;
        Integer d = 128;
        System.out.println(c == d);  // false
      	Integer e = 127;
      	Integer f = new Integer(127);
      	System.out.println(e == f);  // false  重新 new 一个 Integer 对象将不在使用 IntegerCache 中的值
    }
}
分析:
利用 javac test.java && javap -c test.class 查看这次测试 1 - 4 和 6 - 7 行的字节码
Compiled from "test.java"
public class test {
  public test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
  public static void main(java.lang.String[]);
    Code:
       0: bipush        127
       2: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: bipush        127
       8: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      11: astore_2
      12: sipush        128
      15: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      18: astore_3
      19: sipush        128
      22: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      25: astore        4
      27: return
}
可以发现 JAVA运行时发生了如下优化
Integer a = x;
// 优化为
Integer a = Integer.valueOf(x);
以下为 Integer.valueOf(int) 源码
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
可以发现当执行 Integer.valueOf(int) 时, 首先判断 i 是否在 IntegerCache中, 如果是则直接返回其中的值, 如果不是则再 new 一个
注:
直接使用 "==" 比较的是两个对象在内存中的地址, 而 Integer 与 int 比较时 Integer会自动拆箱, 然后比较内存中的数据大小; 若想在 Integer之间比较大小需调用 equals( )方法
拓展:
类似的, Byte 中有 ByteCache, Short 中有 ShortCache, Long 中有 LongCache, 它们的缓存池默认存储范围都是 -128 - 127, 比较规律与 Integer 相同; 但是注意只有 Integer 可以改变缓存大小。

                
            
        
浙公网安备 33010602011771号