java物件的快取
阿新 • • 發佈:2019-01-10
先了看一段非常有意思的程式碼
public class TestIntegerCache {
public static void main(String[] args) {
Integer a = 12;
Integer b = 12;
System.out.println(a == b);//true
System.out.println("=========");
Integer x = 1222;
Integer y = 1222;
System.out.println(x == y);//false
}
}
看到結果是不是有點意外呢,沒關係我們看看編譯過後的java程式碼什麼樣:
public class TestIntegerCache {
//自動建立一個空的建構函式
public TestIntegerCache() {
}
public static void main(String[] args) {
//注意此處呼叫了valueOf()方法,那這個方法是幹嘛用的呢???
Integer a = Integer.valueOf(12);
Integer b = Integer.valueOf(12 );
System.out.println(a == b);
System.out.println("=========");
Integer x = Integer.valueOf(1222);
Integer y = Integer.valueOf(1222);
System.out.println(x == y);
}
}
我們開啟Integer的原始碼:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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;
}
private IntegerCache() {}
}
看到這裡,相信各位看官都會恍然大悟,在類載入位元組碼檔案的時候,會載入jvm配置,為了避免建立重複的物件,看到原始碼我們發現對Integer值做了快取,建立物件的時候會判斷這個值是否在這個範圍內如果這個值在快取-128~127範圍內,直接返回快取好的物件,否則new一個新的物件返回