Java中的整数缓存IntegerCache
所属分类 java
浏览量 1335
-128~127的数字 会缓存起来
该范围内的自动装箱 调用 Integer.valueOf(i)
Integer int1 = 3; 相当于
Integer int1 = Integer.valueOf(3);
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// -XX:AutoBoxCacheMax=256
System.out.println(sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"));
high 可通过参数配置
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() {}
}
Long,Short,Byte,Character 都有类似缓存 , 只有 IntegerCache 可以配置 high 值
测试代码 IntegerCacheTest.java
public class IntegerCacheTest {
public static void main(String[] args) throws Exception {
// -XX:AutoBoxCacheMax=256
System.out.println(sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"));
// 自动装箱
Integer int0 = Integer.valueOf(3);
Integer int1 = 3;
Integer int2 = 3;
Integer int3 = new Integer(3);
System.out.println(int1==int2);
System.out.println(int1==int3);
System.out.println(int1.equals(int3));
Integer int4 = 666;
Integer int5 = 6666;
Integer int6 = new Integer(666);
System.out.println(int4==int5);
System.out.println(int4==int6);
System.out.println(int4.equals(int6));
}
}
上一篇
下一篇
tomcat线程池要点
java线程池系列文章汇总
tomcat参数 acceptCount maxConnections maxThreads
JMX之ObjectName
tomcat之JMXProxyServlet
javap查看字节码