JDK源碼| Integer的IntegerCache(緩存池)

  • Integer緩存池是jdk5中引入的一個有助于節(jié)省內(nèi)存,提高性能的新特性

  • Integer緩存池范圍 -128~127

  • Integer內(nèi)部有一個靜態(tài)內(nèi)部類IntegerCache,里面有一個cache[]數(shù)組,數(shù)組通過for循環(huán)初始化,默認(rèn)大小為(-128~127),

  • 通過JVM啟動參數(shù) -XX:AutoBoxCacheMax=size修改緩存最大值

   // jdk 源碼
    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;
        }
    }

其他整數(shù)類型的類都有類似的緩存機(jī)制:
例如:

  • ByteCache,ShortCache,LongCache 緩存范圍 -128~127
  • CharactorCache 緩存范圍 0~127
  • 注意:只有Integer能修改緩存范圍
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容