本文对JDK8中的java.lang.Integer包装类的部分数值缓存技术、valueOf()、stringSize()、toString()、getChars()、parseInt()等进行简要分析。
Integer缓存
先来看一段代码:
Integer a1 = Integer.valueOf(13);
Integer a2 = Integer.valueOf(13);
Integer a3 = Integer.valueOf(133);
Integer a4 = Integer.valueOf(133);
System.out.println(a1 == a2); // 输出 true
System.out.println(a3 == a4); // 输出 false
两个输出语句具有不同的输出,在于Integer使用了一个静态内部类(嵌套类),里面包含了一个缓存数组cache[],默认情况下,[-128, 127]之间的整数会在第一次使用时(类加载时)被自动装箱,放在cache[]数组里。区间的上限值high设置JVM参数-XX:AutoBoxCacheMax来改变,默认情况下参数为127(byte类型的范围),存储在java.lang.Integer.IntegerCache.high属性中。
// 静态内部类实现[-128, 127]的缓存
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high 值通过JVM进行设置,默认为127
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);
// 最大缓存上限 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.valueOf()进行构造时,就使用了cache[]缓存数组。因此使用该方法构造的Integer对象如果在缓存区间内,会直接返回cache[]数组内的相应的引用,自然就是同一个对象;否则将生成一个全新的Integer对象。与此对应的,如果使用构造函数Integer()直接构造,根本没有使用到缓存数组,生成的一定是全新的Integer对象。因此使用Integer.valueOf()构造能够节省资源,提高效率。
// 使用cache[]数组构造
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// 使用构造函数构造
public Integer(int value) {
this.value = value;
}
stringSize()
这个函数不是个public权限的函数,作为内部工具方法使用。这个方法的实现是很巧妙的,避免除法、求余等,判断条件简单,效率高(采用静态field分析,而不是负责逻辑判断可以明显提高效果)。(int 最大长只有10)
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x 参数必须为正数
static int stringSize(int x) {
for (int i=0; ; i++)