Integer缓存引发的思考

读过JDK源代码的朋友都知道,在基本类型的包装类中,除了FloatDouble以外,其余都有缓存机制:调用valueOf方法时,如果参数值在缓存区间内,则返回一个在类加载时就已创建好的对象,否则new一个对象。这些包装类的缓存范围如下:

    // java.lang.Byte
    // 缓存区间:[-128, 127]
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

    // java.lang.Short
    // 缓存区间:[-128, 127]
    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

    // java.lang.Integer
    // 缓存区间:[-128, 127]
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    // java.lang.Long
    // 缓存区间:[-128, 127]
    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);
    }

    // java.lang.Character
    // 缓存区间:[0, 127]
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }
复制代码

我们知道,static标注的字段、方法、内部类和代码块都是属于类的信息,会在类加载时初始化,而java.lang.Integer等基本类会在JVM启动时就被BootstrapClassloader加载。因此,如果我们使用valueOf方法获取值在[-128, 127]区间的Integer对象,得到的实际上是JVM启动时就已存在的Integer数组中的对象,而无需在Java堆内存中新建对象再获取。

此处拿IntegerCache举例,其余包装类缓存机制雷同,在此便不赘述。

    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() {}
    }
复制代码

关于包装类的缓存机制,笔者还有两点思考:为什么要对较小的数字做缓存?为什么FloatDouble没有缓存?

首先是第一个问题。笔者猜测,从统计学的角度来看,[-128, 127]的数字和[0, 127]的字符在代码中有较大的概率被使用到,因此JDK设计者为他们设计了缓存机制,以免频繁创建不必要的小对象。

其次是第二个问题。我们留意到只有整数和字符有缓存,浮点数则没有。包装类中的这套缓存机制,无非是用循环初始化了一个值域为[-128, 127]或[0, 127]的static final数组存储在堆内存中(JDK 1.7及以后)。Java浮点数是根据 IEEE 754 实现的,显而易见,根据现行的浮点数表示方法,根本不可能效仿整数和字符开辟一个长度较小的数组缓存部分浮点数。

参考资料

猜你喜欢

转载自juejin.im/post/5d5eaf00e51d45620d2cb908