Integer IntegerCache源碼閱讀
先看一段測試結果:
/*public static void main(String[] args) { Integer a = 128, b = 128; Integer c = 127, d = 127; System.out.println(a == b);//false System.out.println(c == d);//true }*/ /*public static void main(String[] args) { Integer int1 = Integer.valueOf("100"); Integer int2 = Integer.valueOf("100"); System.out.println(int1 == int2);//true }*/ public static void main(String[] args) { Integer int1 = Integer.valueOf("300"); Integer int2 = Integer.valueOf("300"); System.out.println(int1 == int2);//false }
JDK的源碼如下:
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); }
發(fā)現(xiàn)里面另有玄機,多了個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把-128到127(可調(diào))的整數(shù)都提前實例化了。
這就解釋了答案,原來你不管創(chuàng)建多少個這個范圍內(nèi)的Integer用ValueOf出來的都是同一個對象。
但是為什么JDK要這么多此一舉呢? 我們仔細想想, 淘寶的商品大多數(shù)都是100以內(nèi)的價格, 一天后臺服務器會new多少個這個的Integer, 用了IntegerCache,就減少了new的時間也就提升了效率。同時JDK還提供cache中high值得可配置,
這無疑提高了靈活性,方便對JVM進行優(yōu)化。
總結
以上就是本文關于Integer IntegerCache源碼閱讀的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05Springboot hibernate envers使用過程詳解
這篇文章主要介紹了Springboot hibernate envers使用過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06spring boot 集成 shiro 自定義密碼驗證 自定義freemarker標簽根據(jù)權限渲染不同頁面(推薦
這篇文章主要介紹了spring-boot 集成 shiro 自定義密碼驗證 自定義freemarker標簽根據(jù)權限渲染不同頁面,需要的朋友可以參考下2018-12-12