Java中的常量类缓存机制

还记得被多个对象的判断==/equals支配的恐惧吗?

随便来一个,

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
Integer i = 12; //1
Integer i1 = 12; //2

Integer i2 = 129; //3
Integer i3 = 129; //4

System.out.println(i == i1); // 5
System.out.println(i2 == i3); //6

}

这个的输出结果是什么呢?

直接展示答案吧,输出结果是:

1
2
true
false

我们来研究一下为什么.

首先我们要知道,在1.5之后的JDK为我们提供了自动装箱与拆箱,用来解决8中基本类型->对象的转换问题,这一点如果不是很清楚了话可以先google了解一下.

上面代码中的语句1-4无疑都是发生了装箱的,那么我们反编译一下这段代码,来看一下在装箱过程中到底发生了什么.

在命令行中执行以下命令:

1
2
javac IntegerTest.java
javap -v -c -s -l IntegerTest

可以看到输出结果如下:

2019-05-12-23-51-36

可以看到自动装箱的时候调用的是Integer.valueOf()方法,那么我们看一下他的实现:

1
2
3
4
5
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

当传入的数字在某个范围(这个范围默认是-128到127)之间时,直接返回缓存的一个列表,找一下缓存列表的初始化的地方:

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
34
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() {}
}

这是IntegerCache缓存类的实现,在类加载的时候用静态方法快进行了初始化,将缓存范围内的值预先加载好放在数组中.

可以看到对缓存范围的上限数字是通过读取配置来设置的,因此,Integer的缓存范围是可以通过参数 -XX:AutoBoxCacheMax=size来设置的.

其他常量类的缓存

这种缓存行为不仅适用于Integer对象。针对所有整数类型的类都有类似的缓存机制。

  1. ByteCache 用于缓存 Byte 对象, 固定范围[-128-127].

  2. ShortCache 用于缓存 Short 对象,固定范围[-128-127].

  3. LongCache 用于缓存 Long 对象,固定范围[-128-127].

  4. CharacterCache 用于缓存 Character 对象, 固定范围[0-127].

而通过参数设置缓存范围,只有Integer可以.其他的都不允许.





ChangeLog

2019-05-10 完成

以上皆为个人所思所得,如有错误欢迎评论区指正。

欢迎转载,烦请署名并保留原文链接。

联系邮箱:huyanshi2580@gmail.com

更多学习笔记见个人博客——>呼延十