Integer的缓存机制

最近看到在Integer中有一些非常巧妙的设计,比如Integer的缓存机制,特此在此分享一下。

首先看一下简单的两个例子:

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
public static void main(String[] args) {
Integer a = new Integer(127);
Integer b = new Integer(127);
if (a == b) {
System.out.println("a==b");
} else {
System.out.println("a!=b");
}

Integer c = 127;
Integer d = 127;
if (c == d) {
System.out.println("c==d");
} else {
System.out.println("c!=d");
}

Integer e = 128;
Integer f = 128;
if (e == f) {
System.out.println("e==f");
} else {
System.out.println("e!=f");
}

Integer g = 128;
int h = 128;
if (g == h) {
System.out.println("g==h");
} else {
System.out.println("g!=h");
}

}

运行结果为:

1
2
3
4
a!=b
c==d
e!=f
g==h

分析

a!=b

因为a和b都是包装类,当两个包装类用==比较时,比较的是其在堆中的地址,而两个基本类型用==比较时,比较的是其在栈中的值。

c==d

首先这里是相等,a和b的初始化方式,是直接将数字赋值,这种方式,在初始化的时候,等价与下面的代码:
Integer a = Integer.valueOf(100);
这里便涉及到了Integer的缓存机制问题, Integer默认是在-128~127的数据是有缓存的。这样,如果初始化-128~127之间的数字,便会直接从内存中取出,而不需要再新建一个对象。

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

以上是初始化的过程,可以发现当iIntegerCache.lowIntegerCache.high之间时,会直接从缓存中取,否则则会new一个新对象,我们再进入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
34
35
36
37
38
39
40
41
42
43
44
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/

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

可以看到,high的值,默认是127, 如果java.lang.Integer.IntegerCache.high的变量有设置,则取这个值。jvm在初始化的时候,会将低值-128到高值默认127之间的数字加载到内存中。
低值是固定的,不能改变,只能是-128,但是高值是可以通过jvm参数改变的。当我们需要改编时,在java程序执行的时候加上 -XX:AutoBoxCacheMax=<size> 的参数即可。

e!=f

同上,当值超过默认的127时,会新new一个对象,所以不相等。

g==h

Integerint的包装类,在和int比较时,会自动拆包成int类型进行比较,所以相等。