Integer IntegerCache源码阅读

2025-05-27 0 41

先看一段测试结果:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
/*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的源码如下:

?

1

2

3

4

5

6

7

8

9
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);

}

发现里面另有玄机,多了个IntegerCache类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33
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(可调)的整数都提前实例化了。

这就解释了答案,原来你不管创建多少个这个范围内的Integer用ValueOf出来的都是同一个对象。

但是为什么JDK要这么多此一举呢? 我们仔细想想, 淘宝的商品大多数都是100以内的价格, 一天后台服务器会new多少个这个的Integer, 用了IntegerCache,就减少了new的时间也就提升了效率。同时JDK还提供cache中high值得可配置,

这无疑提高了灵活性,方便对JVM进行优化。

总结

以上就是本文关于Integer IntegerCache源码阅读的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://www.cnblogs.com/mr-wuxiansheng/p/7498678.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Integer IntegerCache源码阅读 https://www.kuaiidc.com/76419.html

相关文章

发表评论
暂无评论