摘要:本文將介紹 Java 中 Integer 緩存的相關(guān)知識(shí)。這是 Java 5 中引入的一個(gè)有助于節(jié)省內(nèi)存、提高性能的特性。首先看一個(gè)使用 Integer 的示例代碼,展示了 Integer 的緩存行為。接著我們將學(xué)習(xí)這種實(shí)現(xiàn)的原因和目的。你可以先猜猜下面 Java 程序的輸出結(jié)果。很明顯,這里有一些小陷阱,這也是我們寫這篇文章的原因。public class JavaInteg
本文將介紹 Java 中 Integer 緩存的相關(guān)知識(shí)。這是 Java 5 中引入的一個(gè)有助于節(jié)省內(nèi)存、提高性能的特性。首先看一個(gè)使用 Integer 的示例代碼,展示了 Integer 的緩存行為。接著我們將學(xué)習(xí)這種實(shí)現(xiàn)的原因和目的。你可以先猜猜下面 Java 程序的輸出結(jié)果。很明顯,這里有一些小陷阱,這也是我們寫這篇文章的原因。
public class JavaIntegerCache { public static void main(String[] args) { Integer integer1=3; Integer integer2=3; if(integer1==integer2){ System.out.println("integer1==integer2"); }else{ System.out.println("integer1!=integer2"); }<br> Integer integer3=300; Integer integer4=300; if(integer3==integer4){ System.out.println("integer3==integer4"); }else{ System.out.println("integer3!=integer4"); } } }
大多數(shù)人都認(rèn)為上面的兩個(gè)判斷的結(jié)果都是 false。雖然它們的值相等,但由于比較的是對象,而對象的引用不一樣,所以會(huì)認(rèn)為兩個(gè) if 判斷都是 false 的。在 Java 中,== 比較的是對象引用,而 equals 比較的是值。因此,在這個(gè)例子中,不同的對象有不同的引用,所以在進(jìn)行比較的時(shí)候都應(yīng)該返回 false。但是奇怪的是,這里兩個(gè)相似的 if 條件判斷卻返回不同的布爾值。
下面是上面代碼真正的輸出結(jié)果
integer1==integer2 integer3!=integer4
Java 中 Integer 緩存實(shí)現(xiàn)
在 Java 5 中,為 Integer 的操作引入了一個(gè)新的特性,用來節(jié)省內(nèi)存和提高性能。整型對象在內(nèi)部實(shí)現(xiàn)中通過使用相同的對象引用實(shí)現(xiàn)了緩存和重用。
上面的規(guī)則適用于整數(shù)區(qū)間 -128 到 +127。
這種 Integer 緩存策略僅在自動(dòng)裝箱(autoboxing)的時(shí)候有用,使用構(gòu)造器創(chuàng)建的 Integer 對象不能被緩存。
Java 編譯器把原始類型自動(dòng)轉(zhuǎn)換為封裝類的過程稱為自動(dòng)裝箱(autoboxing),這相當(dāng)于調(diào)用 valueOf 方法.
我們來看看 valueOf 的源碼。
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
在創(chuàng)建新的 Integer 對象之前會(huì)先在 IntegerCache.cache 中查找。有一個(gè)專門的 Java 類來負(fù)責(zé) Integer 的緩存。
IntegerCache 類
IntegerCache 是 Integer 類中一個(gè)私有的靜態(tài)類。我們來看看這個(gè)類,有比較詳細(xì)的文檔,可以提供我們很多信息。
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ 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() {} }
Javadoc 詳細(xì)的說明這個(gè)類是用來實(shí)現(xiàn)緩存支持,并支持 -128 到 127 之間的自動(dòng)裝箱過程。最大值 127 可以通過 JVM 的啟動(dòng)參數(shù) -XX:AutoBoxCacheMax=size 修改。 緩存通過一個(gè) for 循環(huán)實(shí)現(xiàn)。從小到大的創(chuàng)建盡可能多的整數(shù)并存儲(chǔ)在一個(gè)名為 cache 的整數(shù)數(shù)組中。這個(gè)緩存會(huì)在 Integer 類第一次被使用的時(shí)候被初始化出來。以后,就可以使用緩存中包含的實(shí)例對象,而不是創(chuàng)建一個(gè)新的實(shí)例(在自動(dòng)裝箱的情況下)。
實(shí)際上在 Java 5 中引入這個(gè)特性的時(shí)候,范圍是固定的 -128 至 +127。后來在 Java 6 中,最大值映射到 java.lang.Integer.IntegerCache.high,可以使用 JVM 的啟動(dòng)參數(shù)設(shè)置最大值。這使我們可以根據(jù)應(yīng)用程序的實(shí)際情況靈活地調(diào)整來提高性能。是什么原因選擇這個(gè) -128 到 127 這個(gè)范圍呢?因?yàn)檫@個(gè)范圍的整數(shù)值是使用最廣泛的。 在程序中第一次使用 Integer 的時(shí)候也需要一定的額外時(shí)間來初始化這個(gè)緩存。
這種緩存行為不僅適用于Integer對象。我們針對所有整數(shù)類型的類都有類似的緩存機(jī)制。
有 ByteCache 用于緩存 Byte 對象
有 ShortCache 用于緩存 Short 對象
有 LongCache 用于緩存 Long 對象
有 CharacterCache 用于緩存 Character 對象
Byte,Short,Long 有固定范圍: -128 到 127。對于 Character, 范圍是 0 到 127。除了 Integer 可以通過參數(shù)改變范圍外,其它的都不行。