Integer中缓存池讲解

一、简介

Integer缓存池是一种优化技术,用于提高整数对象的重用和性能。在Java中,对于整数值在 -128 到 127 之间的整数对象,会被放入缓存池中,以便重复使用。这是因为在这个范围内的整数值被频繁使用,因此重用这些对象可以节省内存和提高性能。当使用自动装箱机制创建整数对象时,如果对象的值在缓存池范围内,会直接返回缓存池中的对象,而不是创建新的对象。这个特性可以通过调用Integer.valueOf(int)方法来实现。

根据通过设置JVM-XX:AutoBoxCacheMax=可以来修改缓存的最大值,最小值改不了

二、实现原理

底层实现的原理是int 在自动装箱的时候会调用IntegervalueOf进而用到了 IntegerCache。

    public static Integer valueOf(String s) throws NumberFormatException {
    
    
        return Integer.valueOf(parseInt(s, 10));
    }

没有太多复杂的步骤,只需要判断给定的值是否在指定范围内,如果是的话,则从 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 类中,数值在 127 以内的两个 Integer 对象会被认为是相等的,而超过 127 的数值则不相等。这是因为在 Java 中,对于数值在 -128 到 127 之间的整型对象,会使用 IntegerCache 中预先初始化的对象。因此,当数值在该范围内时,它们实际上是同一个对象,因此相等性比较会返回 true。这种行为不仅适用于 Integer 类,也适用于 Long 类。

    public static Long valueOf(long l) {
    
    
        final int offset = 128;
        if (l >= -128 && l <= 127) {
    
     // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

对于小数类型的 Float 和 Double,不会有像整数类型那样的缓存机制。因为小数类型的数值范围非常广泛,无法事先预先缓存所有可能的数值。因此,对于 Float 和 Double 类型的对象,相等性比较会根据它们的实际数值来判断,而不是基于对象的引用。所以,即使两个 Float 或两个 Double 对象的数值相同,它们也不会被认为是相等的。

三、修改缓存范围

IntegerCache

通过注释可知缓存值可以修改

IntegerCache

验证:默认情况下

integer

添加JVM参数 -XX:AutoBoxCacheMax=500

AutoBoxCacheMax

再次执行:

integer
发现i1和i2相等返回true,说明参数生效了。

猜你喜欢

转载自blog.csdn.net/qq_39939541/article/details/132309110