Integer緩存池是jdk5中引入的一個有助于節(jié)省內(nèi)存,提高性能的新特性
Integer緩存池范圍 -128~127
Integer內(nèi)部有一個靜態(tài)內(nèi)部類IntegerCache,里面有一個cache[]數(shù)組,數(shù)組通過for循環(huán)初始化,默認(rèn)大小為(-128~127),
通過JVM啟動參數(shù) -XX:AutoBoxCacheMax=size修改緩存最大值
// jdk 源碼
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;
}
}
其他整數(shù)類型的類都有類似的緩存機(jī)制:
例如:
- ByteCache,ShortCache,LongCache 緩存范圍 -128~127
- CharactorCache 緩存范圍 0~127
注意:只有Integer能修改緩存范圍