【发布时间】:2013-02-24 13:31:34
【问题描述】:
Integer 类具有缓存,用于缓存Integer 值。因此,如果我使用方法valueOf 或收件箱,新值将不会被实例化,而是从缓存中获取。
我知道默认缓存大小是127,但可以根据 VM 设置进行扩展。我的问题是:这些设置中缓存大小的默认值有多大,我可以操纵这个值吗?这个值是否取决于我使用的 VM(32 位还是 64 位)?
我现在正在调整遗留代码,可能需要从 int 转换为 Integer。
澄清:我在 Java 源代码中找到的以下代码
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
所以我认为缓存是可配置的。
【问题讨论】:
-
它在Java源代码中。虚拟机设置与它无关。
-
不是从-128到+127吗?我认为它无法更改,除非 vm 允许配置(我从未见过)。
-
您可以使用系统属性
java.lang.Integer.IntegerCache.high设置不同的限制。这一切都在源代码中。 -
如何设置? System.setProperty 还是别的什么?
-
在较早的 java 版本中,它是不可配置的。在 Java 7 中是这样。