Java之IntegerCache

953 阅读2分钟

这是我参与8月更文挑战的第24天,活动详情查看: 8月更文挑战

这是太常见的一道面试题了,而且多用来做笔试题,毕竟有些基础,而且还是个选择题。

IntegerCache,从名称上来看,就是整型数据的缓存,其实从功能上来说,也非常像是缓存概念。

先来看一下常会在笔试题中出现的一道相关题目吧。

public class IntegerTest { 
    public static void main(String [] args) { 
        Integer a = 100, b = 100 ,c = 129,d = 129; 
        System.out.println(a==b); 
        System.out.println(c==d); 
    } 
}

通常还会有几个选项,但是我们在这就不说了,只说一下到底输出了一个什么样的值。

先来正确答案:

true
false

为什么会有这种情况的发生呢?当然就是IntegerCache的作用了,刚才也说了,他提供了缓存功能,但是到底缓存了哪些信息呢?

IntegerCache默认缓存了-128~127的Integer值,只要是在这个范围内的数据,都会直接从IntegerCache中进行获取,无须新创建一个对象。

这个也可以在Integer源码中轻松看出来。

image.png

具体代码如下:

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类中的一个内部类,用于定义常用数值的缓存区,这个缓存区的数字大小范围而且还是可以指定的。

从代码中也可以看出,代码中获取了一个integerCacheHighPropValue值,在这之后,这个值又通过转换后,与127进行选择一个最大值。

也就是说,如果我设置了java.lang.Integer.IntegerCache.high这个参数,也就可以扩大这个缓存区的空间了。

sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high")

那这中取值是如何配置呢,答案是-Djava.lang.Integer.IntegerCache.high