美文网首页
Integer缓存引发的思考

Integer缓存引发的思考

作者: hugo54 | 来源:发表于2019-08-04 23:07 被阅读0次

读过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 实现的,显而易见,根据现行的浮点数表示方法,根本不可能效仿整数和字符开辟一个长度较小的数组缓存部分浮点数。

参考资料

相关文章

  • Integer缓存引发的思考

    读过JDK源代码的朋友都知道,在基本类型的包装类中,除了Float和Double以外,其余都有缓存机制:调用val...

  • Integer缓存机制

    这是Integer中的缓存机制 默认缓存-128~127 Integer integer = 128;我们进...

  • java知识整理-包装类型

    Integer的缓存 Integer内部实现了一个缓存,会缓存-128~127之间的数字。Integer在赋值的时...

  • Java基础-数据类型缓存解析

    基本类型缓存解析 Integer缓存解析: 1、使用自动装箱(Integer i = 1)方式创建Integer对...

  • 深入分析Integer底层原理

    本文将介绍Java中Integer的相关知识,分析Integer缓存的原理和作用。 Integer缓存 在Inte...

  • JDK 源码解析 —— Integer

    说到Java中的Integer包装类,大家或多或少的都听说过Integer缓存,下面我们先从Integer缓存相关...

  • 优秀博客集锦(一)

    理解Java Integer的缓存策略Java中Integer和其他包装类具有缓存机制,会缓存常用的一部分数字。 ...

  • List.remove() 引发的思考

    在码砖的时候用到了接口List的remove方法,该方法有两个overloading变种: 突然想到,如果对于一个...

  • Java装箱类缓存分析

    Integer Integer内部有一个IntegerCache类,这个类用来缓存int型数值,默认缓存的范围是-...

  • 浏览器缓存策略

    最近在对项目做 IE 11 兼容,由 IE 的缓存问题,引发我对于浏览器缓存策略的思考。 缓存类型 web缓存主要...

网友评论

      本文标题:Integer缓存引发的思考

      本文链接:https://www.haomeiwen.com/subject/xuqydctx.html