JAVA基础整理——IntegerCache

首先要重申下,大家都知道的自动拆箱与自动装箱。即

Interge i=100;

代码实际执行的是

Interge i=Integer.valueOf(100);

此处可以打断点调试验证。

接下来我们看下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);
    }

此处可以看见,在一定范围内,返回值为IntegerCahce内的缓存,最后以下Integer的内部类IntegerCahce,如下:

 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把-128到127(可通过JVM参数配置进行调整,增大范围)的整数都提前实例化了。所以不管创建多少个这个范围内的Integer用ValueOf出来的都是同一个对象。

但是为什么JDK要这么多此一举呢? 我们仔细想想, 比如订单的交易数量,大多数都是100以内的价格, 一天后台服务器会new多少个这个的Integer, 用了IntegerCache,就减少了new的时间也就提升了效率。同时JDK还提供cache中high值得可配置,

这无疑提高了灵活性,方便对JVM进行优化。

另外,在Long和Short的源码中,jdk也做了同样的优化

参考Long的源码:

复制代码
private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }
复制代码

Long也做了缓存,只是没有提供调整机制, 在Short中类似:

复制代码
private static class ShortCache {
        private ShortCache(){}

        static final Short cache[] = new Short[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Short((short)(i - 128));
        }
    }
复制代码

 

posted @ 2019-08-03 21:01  豆豆323  阅读(470)  评论(0编辑  收藏  举报