Integer的緩存機制

轉載出處:https://blog.csdn.net/qq_27093465/article/details/52473649

本文將介紹 Java 中 Integer 緩存的相關知識。這是 Java 5 中引入的一個有助於節省內存、提高性能的特性。

首先看一個使用 Integer 的示例代碼,展示了 Integer 的緩存行爲。接着我們將學習這種實現的原因和目的。

你可以先猜猜下面 Java 程序的輸出結果。很明顯,這裏有一些小陷阱,這也是我們寫這篇文章的原因。

[java] view plain copy
  1. /** 
  2.  * 測試Integer的緩存 IntegerCache.cache 
  3.  */  
  4. private static void testIntegerCache() {  
  5.     System.out.println("---int---");  
  6.     int a = 127, b = 127;  
  7.     System.out.println(a == b);         //true  
  8.     a = 128;  
  9.     b = 128;  
  10.     System.out.println(a == b);         //true  
  11.   
  12.     System.out.println("---Integer---");  
  13.     Integer aa = 127, bb = 127;  
  14.     System.out.println(aa == bb);       //true  
  15.     aa = 128;  
  16.     bb = 128;  
  17.     System.out.println(aa == bb);       //false  
  18.     System.out.println(aa.equals(bb));  //true  
  19. }  

執行結果就如同上面的那樣,我就不貼圖來展示啦,我把原文的例子給換成自己的了。

在 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 中的代碼。

[java] view plain copy
  1. /** 
  2.  * Returns an {@code Integer} instance representing the specified 
  3.  * {@code int} value.  If a new {@code Integer} instance is not 
  4.  * required, this method should generally be used in preference to 
  5.  * the constructor {@link #Integer(int)}, as this method is likely 
  6.  * to yield significantly better space and time performance by 
  7.  * caching frequently requested values. 
  8.  * 
  9.  * This method will always cache values in the range -128 to 127, 
  10.  * inclusive, and may cache other values outside of this range. 
  11.  * 
  12.  * @param  i an {@code int} value. 
  13.  * @return an {@code Integer} instance representing {@code i}. 
  14.  * @since  1.5 
  15.  */  
  16. public static Integer valueOf(int i) {  
  17.     if (i >= IntegerCache.low && i <= IntegerCache.high)  
  18.         return IntegerCache.cache[i + (-IntegerCache.low)];  
  19.     return new Integer(i);  
  20. }  

在創建新的 Integer 對象之前會先在 IntegerCache.cache (是個Integer類型的數組)中查找。有一個專門的 Java 類來負責 Integer 的緩存。

IntegerCache 類


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

[java] view plain copy
  1. /** 
  2.  * Cache to support the object identity semantics of autoboxing for values between 
  3.  * -128 and 127 (inclusive) as required by JLS. 
  4.  * 
  5.  * The cache is initialized on first usage.  The size of the cache 
  6.  * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 
  7.  * During VM initialization, java.lang.Integer.IntegerCache.high property 
  8.  * may be set and saved in the private system properties in the 
  9.  * sun.misc.VM class. 
  10.  */  
  11.   
  12. private static class IntegerCache {  
  13.     static final int low = -128;  
  14.     static final int high;  
  15.     static final Integer cache[];  
  16.   
  17.     static {  
  18.         // high value may be configured by property  
  19.         int h = 127;  
  20.         String integerCacheHighPropValue =  
  21.             sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");  
  22.         if (integerCacheHighPropValue != null) {  
  23.             try {  
  24.                 int i = parseInt(integerCacheHighPropValue);  
  25.                 i = Math.max(i, 127);  
  26.                 // Maximum array size is Integer.MAX_VALUE  
  27.                 h = Math.min(i, Integer.MAX_VALUE - (-low) -1);  
  28.             } catch( NumberFormatException nfe) {  
  29.                 // If the property cannot be parsed into an int, ignore it.  
  30.             }  
  31.         }  
  32.         high = h;  
  33.   
  34.         cache = new Integer[(high - low) + 1];  
  35.         int j = low;  
  36.         for(int k = 0; k < cache.length; k++)  
  37.             cache[k] = new Integer(j++);  
  38.   
  39.         // range [-128, 127] must be interned (JLS7 5.1.7)  
  40.         assert IntegerCache.high >= 127;  
  41.     }  
  42.   
  43.     private IntegerCache() {}  
  44. }  

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 可以通過參數改變範圍外,其它的都不行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章