top

关于IntegerCache的一些问题

各位老师好,小弟在学习 JDK7 学习笔记的过程中,对于装箱的内幕这一块,有一些疑惑。

参看了valueOf以及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) {
                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);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }
==================================================
    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
是不是可以这样理解?
IntegerCache在生成之初,就已经将从low至high的每个Integer实例进行创建,并依次放入数组当中。
之后,需要用到valueOf时,会做数值判断,只要值介于low和high之间,就直接返回cache中的对象,而不会调用构造器。
只有超出范围时,才会调用构造器来创建新实例。

那么,是不是说,只要数字在Cache的范围内,任何名牌都会指向同一个实例,也就是判断 == 的话,都会返回true?

另外,用反编译器查看编译程序对代码做的调整。
这一招太棒了~~~!!! 哈哈

TOP

就 JDK 實作看起來是這樣沒錯

TOP

就 JDK 實作看起來是這樣沒錯
codedata 發表於 2013-12-23 10:22



    多谢老师。
还有一事比较不明,就是IntegerCache是在什么时候生成的。
是在创建第一个Integer实例的时候,还是说,从JVM开始跑的时候,就已经生成了。

TOP

IntegerCache 不會有實例,它是 private static class IntegerCache,在 Integer 中都是直接使用其 static 方法 …

你想問的大概是 IntegerCache 中的 static 區塊何時執行,cache 何時會參考到陣列並建立範圍內的 Integer 物件,預設應該是初次載入 IntegerCache 對應的 .class 時,會執行 static 區塊 …

TOP

IntegerCache 不會有實例,它是 private static class IntegerCache,在 Integer 中都是直接使用其 static  ...
codedata 發表於 2013-12-24 12:11



    嗯嗯 了解 非常之感谢~

TOP