Java Integer的緩存策略

1.首先是在valueOf()中出現(xiàn)了對(duì)緩存策略的使用,通過IntegerCache可知當(dāng)-128<=i<=127(默認(rèn))時(shí)候使用了緩存策略。也就是i在范圍內(nèi)的話就從內(nèi)存中取出返回,如果不在范圍內(nèi)就new一個(gè)Integer對(duì)象。

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的一個(gè)靜態(tài)內(nèi)部類:
1)如果設(shè)置了java.lang.IntegerCache.high,就使用這個(gè)值,如果沒有設(shè)置就使用127,java.lang.IntegerCache.high這個(gè)值是通過JVM參數(shù)改變的,在java程序執(zhí)行的時(shí)候加上 -XX:AutoBoxCacheMax=<size> 的參數(shù)即可。
2)使用了斷言assert;
3)其實(shí)所謂的在內(nèi)存中取值,就是在數(shù)組中,可以看出,Integer的值是被存在了cache數(shù)組中的。

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() {}
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 先看一段代碼: 輸出結(jié)果為: 這是為何呢?在 Java 5 中,為 Integer 的操作引入了一個(gè)新的特性,用來...
    Q南南南Q閱讀 2,136評(píng)論 0 5
  • 以下內(nèi)容為作者辛苦原創(chuàng),版權(quán)歸作者所有,如轉(zhuǎn)載演繹請?jiān)凇肮庾儭蔽⑿殴娞?hào)留言申請,轉(zhuǎn)載文章請?jiān)陂_始處顯著標(biāo)明出處。...
    光變閱讀 1,797評(píng)論 3 6
  • 本文將介紹Java中Integer的緩存相關(guān)知識(shí)。這是在Java 5中引入的一個(gè)有助于節(jié)省內(nèi)存、提高性能的功能。首...
    編程鴨閱讀 293評(píng)論 0 0
  • 本文將介紹Java中Integer的緩存相關(guān)知識(shí)。這是在Java 5中引入的一個(gè)有助于節(jié)省內(nèi)存、提高性能的功能。首...
    墨雨軒夏閱讀 565評(píng)論 0 10
  • 吾好美腿,閱腿無數(shù),心有八字,品評(píng)優(yōu)劣,私藏多年,今日共享。 先總八字:“白嫩光潔,渾圓修長”。次做分類:前四字論...
    絕對(duì)瘋了閱讀 373評(píng)論 0 0

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