本文将介绍一下Java中关于Integer的缓存知识,首先看一下下面的代码,猜测一下会输出什么结果。

1. /**
2. * Created by lanxing on 16-3-13.
3. */
4. public class IntegerCache {
5. public static void main(String[] args){
6. 3;
7. 3;
8. System.out.println(integer1 == integer2);
9.
10. 300;
11. 300;
12. System.out.println(integer3 == integer4);
13. }
14. }

对于上述代码,由于运用的是“==”,而java中“==”比较的是两个引用而非引用的值,所以大家普遍认为两个输出都会是false,然而运行结果则为true,false。

Java中关于Integer缓存机制的介绍:

由于上述代码进行了自动装包操作,查看Java的Integer源码的valueOf(int)代码如下:

1. /**
2. * Returns an {@code Integer} instance representing the specified
3. * {@code int} value. If a new {@code Integer} instance is not
4. * required, this method should generally be used in preference to
5. * the constructor {@link #Integer(int)}, as this method is likely
6. * to yield significantly better space and time performance by
7. * caching frequently requested values.
8. *
9. * This method will always cache values in the range -128 to 127,
10. * inclusive, and may cache other values outside of this range.
11. *
12. * @param i an {@code int} value.
13. * @return an {@code Integer} instance representing {@code i}.
14. * @since 1.5
15. */
16. public static Integer valueOf(int i) {
17. if (i >= IntegerCache.low && i <= IntegerCache.high)
18. return IntegerCache.cache[i + (-IntegerCache.low)];
19. return new Integer(i);
20. }

由上述源码可知,当装包对象在IntegerCache.low到Integer.high之间时,结果直接从IntegerCache中获取,否则直接创造一个实例。下面为IntegerCache的源码:

1. /**
2. * Cache to support the object identity semantics of autoboxing for values between
3. * -128 and 127 (inclusive) as required by JLS.
4. *
5. * The cache is initialized on first usage. The size of the cache
6. * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
7. * During VM initialization, java.lang.Integer.IntegerCache.high property
8. * may be set and saved in the private system properties in the
9. * sun.misc.VM class.
10. */
11.
12. private static class IntegerCache {
13. static final int low = -128;
14. static final int high;
15. static final Integer cache[];
16.
17. static {
18. // high value may be configured by property
19. int h = 127;
20. String integerCacheHighPropValue =
21. "java.lang.Integer.IntegerCache.high");
22. if (integerCacheHighPropValue != null) {
23. try {
24. int i = parseInt(integerCacheHighPropValue);
25. 127);
26. // Maximum array size is Integer.MAX_VALUE
27. 1);
28. catch( NumberFormatException nfe) {
29. // If the property cannot be parsed into an int, ignore it.
30. }
31. }
32. high = h;
33.
34. new Integer[(high - low) + 1];
35. int j = low;
36. for(int k = 0; k < cache.length; k++)
37. new Integer(j++);
38.
39. // range [-128, 127] must be interned (JLS7 5.1.7)
40. assert IntegerCache.high >= 127;
41. }

分析上述源码可知,IntegerCache的low为-128,而high可以通过"-XX:AutoBoxCacheMax=<size>"指定,默认的high为127。当设置high之后,high的实际值取默认值和设置值中最大值,同时小于或等于0X7FFFFF7E。然后将low到high之间的数值存放到cache中。由于该类及方法都是静态的,因此在首次使用时会执行该操作,当需要对low到high之间的数字进行装包操作时,则直接返回IntegerCache.cache中现成的引用。所以上述对基本类型3进行装包时返回同一个引用,故结果输出true。

当然,Java中除了对Integer有缓存机制外,其中还有ByteCache,ShortCache,LongCache,CharacterCache分别对其对应的类型进行缓存,其中Byte,Short,Long的缓存范围都为-128——127,Character为0——127。特别要注意的是这几个缓存中,只有Integer的缓存上限(high)可以设置,其他的都不能进行设置,为固定范围。