Integer緩存IntegerCache詳解
Integer緩存IntegerCache詳解
例子代碼
public class IntegerCacheTest {
public static void main(String[] args) {
Integer a=100;
Integer b=100;
System.out.println(a==b);
Integer c=129;
Integer d=129;
System.out.println(c==d);
}
}
運行結果

小朋友你是否有很多問號
源碼詳解
//緩存以支持 JLS 要求的 -128 到 127(含)值的自動裝箱的對象標識語義。緩存在首次使用時初始化。緩存的大小可以由選項 -XX:AutoBoxCacheMax=<size> 控制。在 VM 初始化期間,可以設置 java.lang.Integer.IntegerCache.high 屬性并將其保存在 jdk.internal.misc.VM 類的私有系統屬性中。警告:緩存使用 CDS 存檔,并在運行時從共享存檔重新加載。存檔緩存 (Integer[]) 和 Integer 對象駐留在封閉的存檔堆區域中。更改實現時應小心,并且在初始化后不應為緩存數組分配新的 Integer 對象。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
/**
返回表示 Integer 指定 int 值的實例。如果不需要新 Integer 實例,則通常應優先使用此方法而不是構造函數 Integer(int),因為此方法可能會通過緩存頻繁請求的值來產生顯著更好的空間和時間性能。此方法將始終緩存 -128 到 127(含)范圍內的值,并且可能會緩存此范圍之外的其他值。
參數:
i – 一個 int 值。
返回:
一個 Integer 表示 i的實例。
*/
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
也就是這樣說的
如果i >= IntegerCache.low && i <= IntegerCache.high則調用IntegerCache.cache[i + (-IntegerCache.low)]
如果i的值不滿足i >= IntegerCache.low && i <= IntegerCache.high則調用new Integer(i)
IntegerCache緩存區間為[-128,127] 所以,在調用Integer.valueOf(int i)方法的時候自動裝箱 如果i的值在[-128,127]區間則生成的Integer對象就會被存入緩沖區。當再次對該值進行裝箱時會先去緩沖區中獲取;如果取到則返回,如果沒有取到就創建包裝類對象存入緩沖區并返回
當然了除了Integer之外其他的包裝類也是有這樣的特性的,可以更好地節省內存、提高性能,這應該就是這個特性的出發點吧,而且考慮到了高頻的數值的應用場景闊葉樹設計的很合理,優化的很好

浙公網安備 33010602011771號