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

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

Integer i1 = 1000;
Integer i2 = 1000;
System.out.println(i1 == i2);
// 这里输入为false,因为Integer类型使用==进行比较时,比较的是i1和i2存的内存地址

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
// 这里输出为true,断点调试中可以看到i1和i2存的地址是不一样的,所以可以佐证,JVM会对特定范围整数进行缓存
复制代码

我们可以查看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的不可变性

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

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

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

猜你喜欢

转载自juejin.im/post/7018134510168440869