日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Integer 中的缓存类IntegerCache

發(fā)布時間:2023/12/10 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Integer 中的缓存类IntegerCache 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2014年去某公司筆試的時候遇到這么一道題:

public class Test {public static void main(String[] args) {Integer int1 = Integer.valueOf("100");Integer int2 = Integer.valueOf("100");System.out.println(int1 == int2);} }

問打印的結(jié)果的多少? 但是我回答的是false, 后來仔細想想應(yīng)該沒有這個簡單,就翻了下JDK的源碼,發(fā)現(xiàn):

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 propertyint 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_VALUEh = 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)的價格, 一天后臺服務(wù)器會new多少個這個的Integer, 用了IntegerCache,就減少了new的時間也就提升了效率。同時JDK還提供cache中high值得可配置,

這無疑提高了靈活性,方便對JVM進行優(yōu)化。

?

參考Long的源碼:

private static class LongCache {private LongCache(){}static final Long cache[] = new Long[-(-128) + 127 + 1];static {for(int i = 0; i < cache.length; i++)cache[i] = new Long(i - 128);}}

Long也做了緩存,只是沒有提供調(diào)整機制, 在Short中類似:

private static class ShortCache {private ShortCache(){}static final Short cache[] = new Short[-(-128) + 127 + 1];static {for(int i = 0; i < cache.length; i++)cache[i] = new Short((short)(i - 128));}}

?

轉(zhuǎn)載于:https://www.cnblogs.com/wellmaxwang/p/4422855.html

總結(jié)

以上是生活随笔為你收集整理的Integer 中的缓存类IntegerCache的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。