IntegerCache类

先看代码实例现象:

IntegerCache类

问题:为什么都是比较数值,第一个为true,第二个确为false呢?

查找源码(java.lang.Integer),看到如下代码:

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

原来是因为Integer类型使用了缓存机制,即默认在JVM启动的时候设定了[-127~128]范围内的int包装类,这样在实际使用并在范围内的时候,直接从缓存中取实例,不用再new了。

这样做的好处是:提升JVM的性能。

坏处是:用==来比较Integer类型的时候,可能出现问题。

解决方案:

  • 设定JVM启动参数-XX:AutoBoxCacheMax=<size>,改编默认的缓存最大(不推荐)
  • 不要用==比较大小,用equals比较(推荐)

同样使用缓存的还有ShortCache, LongCache

上一篇:php json_decode


下一篇:原生js学习笔记2