Java Integer的缓存策略

2019-04-24  本文已影响0人  炖土豆块

1.首先是在valueOf()中出现了对缓存策略的使用,通过IntegerCache可知当-128<=i<=127(默认)时候使用了缓存策略。也就是i在范围内的话就从内存中取出返回,如果不在范围内就new一个Integer对象。

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

2.IntegerCache是Integer的一个静态内部类:
1)如果设置了java.lang.IntegerCache.high,就使用这个值,如果没有设置就使用127,java.lang.IntegerCache.high这个值是通过JVM参数改变的,在java程序执行的时候加上 -XX:AutoBoxCacheMax=<size> 的参数即可。
2)使用了断言assert;
3)其实所谓的在内存中取值,就是在数组中,可以看出,Integer的值是被存在了cache数组中的。

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() {}
    }
上一篇 下一篇

猜你喜欢

热点阅读