整数缓存有多大?

Integer具有缓存,缓存Integer值。 因此,如果我使用方法valueOf或inboxing,新值将不会被实例化,而是从缓存中获取。

我知道默认缓存大小为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 = 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } 

所以我认为缓存是可配置的。

内部Java实现无法配置,范围从-128到127 。 您可以查看Javadocs或只是查看来源:

 public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } 

UPD。错了 (对Marco Topolnik来说)。 以上所有内容都与较旧的Java实现有关。 对于Java 7,可以使用系统属性实现:

 -Djava.lang.Integer.IntegerCache.high= 

或JVM设置:

 -XX:AutoBoxCacheMax= 

UPD。 2 java.math.BigInteger具有值为-16 <= x <= 16的硬编码缓存。 来自:

  private final static int MAX_CONSTANT = 16; private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1]; private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]; static { for (int i = 1; i <= MAX_CONSTANT; i++) { int[] magnitude = new int[1]; magnitude[0] = i; posConst[i] = new BigInteger(magnitude, 1); negConst[i] = new BigInteger(magnitude, -1); } } public static BigInteger valueOf(long val) { // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant if (val == 0) return ZERO; if (val > 0 && val <= MAX_CONSTANT) return posConst[(int) val]; else if (val < 0 && val >= -MAX_CONSTANT) return negConst[(int) -val]; return new BigInteger(val); } 

对于Java 7,我无法在Oracle的java文档中找到使用-XX:+ AggressiveOpts时究竟会发生什么变化的描述。 所以我运行了一个过程,以确定在我们的实验室中有一个java版本的应用程序服务器上的响应值对于jvm设置的影响:{quote} java version“1.7.0_15”Java(TM)SE运行时环境(版本1.7.0_15) -b03){quote}

该过程是在禁用了aggressiveopts的情况下运行java:java -d64 -server -XX:-AggressiveOpts -XX:+ UnlockDiagnosticVMOptions -XX:+ PrintFlagsFinal -version

该过程是在启用了aggressiveopts的情况下运行java:java -d64 -server -XX:+ AggressiveOpts -XX:+ UnlockDiagnosticVMOptions -XX:+ PrintFlagsFinal -version

这个过程产生了这些差异:

bool AggressiveOpts false – > true {product}

intx AutoBoxCacheMax 128 – > 20000 {C2产品}

intx BiasedLockingStartupDelay 4000 – > 500 {product}

bool EliminateAutoBox false – > true {C2 diagnostic}

来自Javadoc :

public static Integer valueOf(int i)

返回表示指定int值的Integer实例。 如果不需要新的Integer实例,通常应优先使用此方法,而不是构造函数Integer(int),因为此方法可能通过缓存频繁请求的值来显着提高空间和时间性能。 此方法将始终缓存-128到127 (包括端点) 范围内的值 ,并可以缓存此范围之外的其他值。

但你真的不应该依赖于此或试图改变这一点。 这是JVM的实现细节,不应影响您的实现。