Integer 缓存池中的 IntegerCache 源码分析

111 阅读3分钟

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:AutoBoxCacheMa 选项修改 cache 的大小

源码分析

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {   // 静态初始化块, 确保在仅在第一次创建Integer对象时初始化cache
            // 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() {}
    }

Demo

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 对象。

PS:直接使用 "==" 比较的是两个对象在内存中的地址。但如果是 Integer == int 这种情况,Integer 会自动拆箱,然后进行 int 与 int 类型之间的比较,这个比较过程是直接进行“值与值”的比较,而不是内存地址。类似的,在 Java 中,基础数据类型的 == 比较,都是“值与值”的比较。对于引用类型间的 == 比较,比较的才是对应的内存地址,除非重写 equals 方法,自定义比较规则,然后再使用 equals 方法来比较。

拓展

类似的,Byte 中有 ByteCache,Short 中有 ShortCache,Long 中有 LongCache。它们的缓存池默认存储的范围都是 -128 到 127, 比较规律与 Integer 相同。但是注意只有 Integer 可以通过 JVM 的启动参数来改变缓存池的大小。