理解Java Integer的快取策略

importnew發表於2016-04-04

本文將介紹 Java 中 Integer 快取的相關知識。這是 Java 5 中引入的一個有助於節省記憶體、提高效能的特性。首先看一個使用 Integer 的示例程式碼,展示了 Integer 的快取行為。接著我們將學習這種實現的原因和目的。你可以先猜猜下面 Java 程式的輸出結果。很明顯,這裡有一些小陷阱,這也是我們寫這篇文章的原因。

package com.javapapers.java;

public class JavaIntegerCache {
    public static void main(String... strings) {

        Integer integer1 = 3;
        Integer integer2 = 3;

        if (integer1 == integer2)
            System.out.println("integer1 == integer2");
        else
            System.out.println("integer1 != integer2");

        Integer integer3 = 300;
        Integer integer4 = 300;

        if (integer3 == integer4)
            System.out.println("integer3 == integer4");
        else
            System.out.println("integer3 != integer4");

    }
}

大多數人都認為上面的兩個判斷的結果都是 false。雖然它們的值相等,但由於比較的是物件,而物件的引用不一樣,所以會認為兩個 if 判斷都是 false 的。在 Java 中,== 比較的是物件引用,而 equals 比較的是值。因此,在這個例子中,不同的物件有不同的引用,所以在進行比較的時候都應該返回 false。但是奇怪的是,這裡兩個相似的 if 條件判斷卻返回不同的布林值。

下面是上面程式碼真正的輸出結果,

integer1 == integer2
integer3 != integer4

Java 中 Integer 快取實現

在 Java 5 中,為 Integer 的操作引入了一個新的特性,用來節省記憶體和提高效能。整型物件在內部實現中通過使用相同的物件引用實現了快取和重用。

上面的規則適用於整數區間 -128 到 +127。

這種 Integer 快取策略僅在自動裝箱(autoboxing)的時候有用,使用構造器建立的 Integer 物件不能被快取。

Java 編譯器把原始型別自動轉換為封裝類的過程稱為自動裝箱(autoboxing),這相當於呼叫 valueOf 方法

Integer a = 10; //this is autoboxing
Integer b = Integer.valueOf(10); //under the hood

現在我們知道了 JDK 原始碼中對應實現的部分在哪裡了。我們來看看 valueOf 的原始碼。下面是 JDK 1.8.0 build 25 中的程式碼。

 /**
     * Returns an {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance representing the specified
     * {<a href="http://www.jobbole.com/members/java12">@code</a> int} value.  If a new {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {<a href="http://www.jobbole.com/members/57845349">@link</a> #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 {<a href="http://www.jobbole.com/members/java12">@code</a> int} value.
     * @return an {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance representing {<a href="http://www.jobbole.com/members/java12">@code</a> i}.
     * <a href="http://www.jobbole.com/members/chchxinxinjun">@since</a>  1.5
     */
    public static Integer valueOf(int i) {
        if (i &amp;gt;= IntegerCache.low &amp;amp;&amp;amp; i &amp;lt;= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

在建立新的 Integer 物件之前會先在 IntegerCache.cache 中查詢。有一個專門的 Java 類來負責 Integer 的快取。

IntegerCache 類

IntegerCache 是 Integer 類中一個私有的靜態類。我們來看看這個類,有比較詳細的文件,可以提供我們很多資訊。

/**
     * 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 {<a href="http://www.jobbole.com/members/java12">@code</a> -XX:AutoBoxCacheMax=} 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) {
                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 &amp;lt; cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high &amp;gt;= 127;
        }

        private IntegerCache() {}
    }

Javadoc 詳細的說明這個類是用來實現快取支援,並支援 -128 到 127 之間的自動裝箱過程。最大值 127 可以通過 JVM 的啟動引數 -XX:AutoBoxCacheMax=size 修改。 快取通過一個 for 迴圈實現。從小到大的建立儘可能多的整數並儲存在一個名為 cache 的整數陣列中。這個快取會在 Integer 類第一次被使用的時候被初始化出來。以後,就可以使用快取中包含的例項物件,而不是建立一個新的例項(在自動裝箱的情況下)。

實際上在 Java 5 中引入這個特性的時候,範圍是固定的 -128 至 +127。後來在 Java 6 中,最大值對映到 java.lang.Integer.IntegerCache.high,可以使用 JVM 的啟動引數設定最大值。這使我們可以根據應用程式的實際情況靈活地調整來提高效能。是什麼原因選擇這個 -128 到 127 這個範圍呢?因為這個範圍的整數值是使用最廣泛的。 在程式中第一次使用 Integer 的時候也需要一定的額外時間來初始化這個快取。

Java 語言規範中的快取行為

在 Boxing Conversion 部分的Java語言規範(JLS)規定如下:

如果一個變數 p 的值屬於:-128至127之間的整數(§3.10.1),true 和 false的布林值 (§3.10.3),’u0000′ 至 ‘u007f’ 之間的字元(§3.10.4)中時,將 p 包裝成 a 和 b 兩個物件時,可以直接使用 a == b 判斷 a 和 b 的值是否相等。

其他快取的物件

這種快取行為不僅適用於Integer物件。我們針對所有整數型別的類都有類似的快取機制。

有 ByteCache 用於快取 Byte 物件

有 ShortCache 用於快取 Short 物件

有 LongCache 用於快取 Long 物件

有 CharacterCache 用於快取 Character 物件

Byte,Short,Long 有固定範圍: -128 到 127。對於 Character, 範圍是 0 到 127。除了 Integer 可以通過引數改變範圍外,其它的都不行。

相關文章