Java自動(dòng)裝箱和拆箱,包裝類(lèi)緩存機(jī)制和JVM調(diào)節(jié)

關(guān)于Java自動(dòng)裝箱和拆箱

  • 基本數(shù)據(jù)(Primitive)類(lèi)型的自動(dòng)裝箱(autoboxing)、拆箱(unboxing)是自J2SE 5.0開(kāi)始提供的功能
  • 自動(dòng)裝箱,個(gè)人感覺(jué)也就是為了所謂的java泛型,泛型就是一種糖,裝箱是一種糖也就更好解釋了。并且兩者都是編譯器提供的,都存在于編譯期(當(dāng)然編譯器做的越多,JVM就可以解釋的越快),我想通過(guò)反編譯,可以輕松的發(fā)現(xiàn)。
  • 自動(dòng)裝箱:把基本類(lèi)型用它們對(duì)應(yīng)的引用類(lèi)型包裝起來(lái),使它們具有對(duì)象的特質(zhì) Integer a=3(Integer源碼,注釋的信息量很大啊( ̄ ̄)")
/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    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);
    }
  • 自動(dòng)拆箱:將Integer及Double這樣的引用類(lèi)型的對(duì)象重新簡(jiǎn)化為基本類(lèi)型的數(shù)據(jù) int i = new Integer(2)
    /**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }

基本類(lèi)型防迷惑

  • 基本類(lèi)型不管多大,==都返回true,因?yàn)榛绢?lèi)型不會(huì)比較地址,更不存在equals
        /**
         * 基本類(lèi)型不管多大,==都返回true,因?yàn)榛绢?lèi)型不會(huì)比較地址,更不存在equals
         */
        int a1 = 121,a2 = 121;
        int b1 = 128,b2 = 128;
        System.out.println(a1 == a2);//true
        System.out.println(b1 == b2);//true

包裝類(lèi)所提供的緩存機(jī)制

  • 每個(gè)整形的包裝類(lèi),包括Long、Integer、Short、Byte、Character,都提供了緩存機(jī)制(一種優(yōu)化手段),但是Float、Double沒(méi)有,也就沒(méi)有==比較的有趣現(xiàn)象了。
        //Integer
        Integer l1 = 12;
        Integer l2 = 12;
        Integer l3 = 128;
        Integer l4 = 128;
        System.out.println(l1 == l2);//true
        System.out.println(l3 == l4);//false
        //Long
        Long l5 = 128L;
        Long l6 = 128L;
        System.out.println(l5 == l6);//false
        Double d1 = 12d;
        Double d2 = 12d;
        System.out.println(d1 == d2);//false
  • 調(diào)整JVM參數(shù)-XX:AutoBoxCacheMax=250,最大緩存值可以達(dá)到-128—250 ,只能調(diào)整上限,這和Integer緩存算法實(shí)現(xiàn)有關(guān),當(dāng)然這個(gè)參數(shù)只對(duì)Integer有效,Long...無(wú)法調(diào)節(jié),通過(guò)源碼可以清楚的看到這一點(diǎn)。
    /**
     * 調(diào)節(jié)虛擬機(jī)參數(shù):-XX:AutoBoxCacheMax=250后,最大緩存值可以達(dá)到-128——250
     */
    @org.junit.Test
    public void test2(){
        Integer l3 = 250;
        Integer l4 = 250;
        System.out.println(l3 == l4);//true
    }
  • 關(guān)于包裝類(lèi)的equals
    /**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is an {@code Integer} object that
     * contains the same {@code int} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
  • 關(guān)于==,說(shuō)-128—127存在所謂的常量池因?yàn)榫彺婢褪且粋€(gè)靜態(tài)數(shù)組,可以認(rèn)為存在常量池),不如說(shuō)是整形包裝類(lèi)停供的緩存機(jī)制,因?yàn)楫?dāng)-128—127是從緩存(xxxCache數(shù)組)中取。
  • 每一個(gè)整形包裝類(lèi)里面都有一個(gè),私有靜態(tài)內(nèi)部類(lèi)XXXCache,里面含有對(duì)應(yīng)類(lèi)型的固定長(zhǎng)度(其實(shí)通過(guò)JVM參數(shù)可以調(diào)節(jié))的final cache數(shù)組 。見(jiàn)下面源碼(注意注釋):
  /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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() {}
    }

再看一下Long的(很簡(jiǎn)單):

   private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }

  • 再看一下valueOf的源碼,就會(huì)發(fā)現(xiàn)如果值在-128—127,會(huì)直接從cache(就是一個(gè)數(shù)組,在XXXCache私有靜態(tài)內(nèi)部類(lèi)中)中取。
    public static Long valueOf(long l) {
        final int offset = 128;
        //判斷
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        //否則直接返回new出來(lái)的
        return new Long(l);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,628評(píng)論 18 399
  • 引入 == 基本數(shù)據(jù)類(lèi)型(也稱(chēng)原始數(shù)據(jù)類(lèi)型) :byte,short,char,int,long,float,do...
    凱諾婷閱讀 1,304評(píng)論 1 7
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,890評(píng)論 0 33
  • 自動(dòng)裝箱和拆箱從Java 1.5開(kāi)始引入,目的是將原始類(lèi)型值轉(zhuǎn)自動(dòng)地轉(zhuǎn)換成對(duì)應(yīng)的對(duì)象。自動(dòng)裝箱與拆箱的機(jī)制可以讓我...
    codersm閱讀 452評(píng)論 0 0

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