天天看點

Integer中的緩存IntegerCache

不知道你有沒有遇到過這樣的問題?

public class Test {
	public static void main(String[] args) {
		Integer i1 = 100;
	       Integer i2 = 100;
	       System.out.println(i1 == i2);
		Integer i3 = 1000;
	       Integer i4 = 1000;
	       System.out.println(i3 == i4);
	}
}
           

運作之後的結果是:true,false

考到結果你一定會很驚訝,what?發生了什麼?

根據Java編譯機制,在編譯器編譯代碼時,在聲明的變量上加入了valueOf方法:

public class Test {
	public static void main(String[] args) {
		Integer i1 = Integer.valueOf(100);
		Integer i2 = Integer.valueOf(100);
		System.out.println(i1 == i2);
		Integer i3 = Integer.valueOf(1000);
		Integer i4 = Integer.valueOf(1000);
		System.out.println(i3 == i4);
	}
}
           

讓我們來看看valueOf的實作原理

public static Integer valueOf(String s) throws NumberFormatException {
	return Integer.valueOf(parseInt(s, 10));
}

public static Integer valueOf(int i) {
       if (i >= IntegerCache.low && i <= IntegerCache.high)
       		return IntegerCache.cache[i + (-IntegerCache.low)];//判斷是否在緩存數組裡,如果在,直接傳回
       return new Integer(i);//不在緩存的數組裡,直接new一個新的對象傳回
}
           

我們發現,Integer的作者在寫這個類時,為了避免重複建立對象,對Integer值做了緩存,如果這個值在緩存範圍内,直接傳回緩存對象,否則new一個新的對象傳回。那究竟這個緩存中有什麼内容呢?看一下IntegerCache這個類:

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() {}                                                                                       
}
           

這是一個内部靜态類,該類隻能在Integer這個類的内部通路,這個類在初始化的時候,會去加載JVM的配置,如果有值,就用配置的值初始化緩存數組,否則就緩存-128到127之間的值。

再來看之前的代碼:

public class Test {
	public static void main(String[] args) {
		Integer i1 = 100;//取同一數組裡的對象傳回,i1,i2指向同一對象,傳回true
	       Integer i2 = 100;
	       System.out.println(i1 == i2);
		Integer i3 = 1000;//這個相當于new了兩個對象,==比較的是引用變量的記憶體位址,是以為false
	       Integer i4 = 1000;
	       System.out.println(i3 == i4);
	}
}