Java的JVM数值缓存和Integer的不可变性

696 阅读3分钟

Integer类型部分整数会被JVM进行缓存,因为这些数值使用频繁,从而避免冗余的内存碎片。具体范围为-128~127。

我们可以查看Integer的Class源码中的静态类IntegerCache,意思就是使用-128-127的值就会使用缓存。

    /**
     * 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 i1 = 127会自动装箱,而装箱的实现是通过Integer.valueOf,可以看看源码逻辑。

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

如果是缓存区域之内的值则取常量池中已缓存的值,不在-128-127范围内则取一个新的Integer对象
因此可以解释下面的例子中==运算的比较结果。

Integer i1 = 1000;
Integer i2 = 1000;
System.out.println(i1 == i2);
// 这里输出为false,因为Integer类型使用==进行比较时,比较的是i1和i2存的内存地址
// 根据自动装箱规则,1000并不在缓存区间中,所以两个变量存的是两个不同的new Integer(1000)的对象

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
// 这里输出为true,断点调试中可以看到i1和i2存的地址是一样的
// 两个变量的引用地址实际都是源码中IntegerCache.cache[127 + (-IntegerCache.low)]的缓存值

Integer i1 = new Integer(127);
Integer i2 = 127;
System.out.println(i1 == i2);
// 这里输出false,因为缓存机制,变量i2指向源码中IntegerCache.cache[127 + (-IntegerCache.low)]的内存地址
// 而i1变量指向的堆中新建的对象new Integer(127)的内存地址
// 两者在内存中的地址不同

Integer i1 = new Integer(127);
int i2 = 127;
System.out.println(i1 == i2);
// 这里输出true,是因为引用类型Integer和int基础类型进行比较时,Integer类型会自动拆箱
// 而拆箱会调用Integer实例的intValue方法,方法返回成员属性value,实际是两个基础数据类型进行比较值

// Integer源码
private final int value;

public int intValue() {
    return value;
}

以上例子可以佐证,JVM确实会对特定范围整数进行缓存,以及能推断出Integer和int之间各种比较的逻辑。

Integer的不可变性

源码中从未提供过修改Integer值的方法。所以实际每次进行数值运算时,都是创建一个新的Integer对象,并将新对象的引用地址赋值给变量。可以打断点进行调试验证。

Integer i = 1;
// 运行到此处时,i存的地址是Integer@490

i += 1;
// 执行完运算后,此时i存的地址是Integer@491