Integer缓存机制
2020-03-21 本文已影响0人
zfz_amzing
Intgeter的缓存机制
Integer缓存的源码如下,IntegerCache在类加载的时候,创建了256个缓存Integer对象,范围在-128~127.
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
VM.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的值-128到127之间时,会引用缓存中创建好的对象,不会创建新的对象所以num1 ==num2
输出为true。
超过这个范围就会创建新的对象,num3 == num4
输出为false
public static void main(String argv[]){
Integer num1 = 1;
Integer num2 = 1;
Integer num3 = 129;
Integer num4 = 129;
System.out.println(num1 == num2); //true
System.out.println(num3 == num4); //false
}