當使用自動裝箱的時候,也就是將基本數據類型傳遞給對象類的時候觸發自動裝箱。這個時候java虛擬機會創建一系列的整數並且緩存到一個數組中以便直接使用,這就是緩存策略。
===自動裝箱機制
Java 編譯器把原始類型自動轉換為封裝類的過程稱為自動裝箱(autoboxing),這相當於調用 valueOf 方法
Integer a = 10; //this is autoboxing
Integer b = Integer.valueOf(10); //under the hood
=== Integer 緩存策略
這種 Integer 緩存策略僅在自動裝箱(autoboxing)的時候有用,使用構造器創建的 Integer 對象不能被緩存。
上面的規則適用於整數區間 -128 到 +127。
因為Integer.valueof就是緩存策略執行的地方
===Integer.valueof(int i)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
===IntegerCache
Javadoc 詳細的說明這個類是用來實現緩存支持,並支持 -128 到 127 之間的自動裝箱過程。最大值 127 可以通過 JVM 的啟動參數 -XX:AutoBoxCacheMax=size 修改。 緩存通過一個 for 循環實現。從小到大的創建盡可能多的整數並存儲在一個名為 cache 的整數數組中。這個緩存會在 Integer 類第一次被使用的時候被初始化出來。以后,就可以使用緩存中包含的實例對象,而不是創建一個新的實例(在自動裝箱的情況下)。
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;
}
p
===其他緩沖行為
其他緩存的對象
這種緩存行為不僅適用於Integer對象。我們針對所有整數類型的類都有類似的緩存機制。
有 ByteCache 用於緩存 Byte 對象
有 ShortCache 用於緩存 Short 對象
有 LongCache 用於緩存 Long 對象
有 CharacterCache 用於緩存 Character 對象
Byte,Short,Long 有固定范圍: -128 到 127。對於 Character, 范圍是 0 到 127。除了 Integer 可以通過參數改變范圍外,其它的都不行。