您的位置:首页 > 编程语言 > Java开发

关于java基本数据类型的包装类的自动装箱池的大小

2012-07-15 13:04 549 查看
一直以为Integer的自动装箱池的大小是-128~127,今天看了jdk1.6的源代码,发现其实并不一定的。

大家都知道java有8种基本类型,它们都有自己的包装类。而Byte,Character,Short,Integer,Long都有一个自动装箱池,我一开始以为除了Character的自动装箱池的大小为0~127以外,其他都是-128~127。但是我在看jdk源代码的时候发现Integer的自动装箱池的实现跟其他几个包装类并不一样,我们先来看看Integer类好Short两个包装类的实现。

Integer类的自动装箱池的实现:

private static class IntegerCache {
static final int high;
static final Integer cache[];

static {
final int low = -128;

// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
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() {}
}


Short和其他包装类(Character除外,不过原理一样,只是范围不一样)的自动装箱池的实现:

private static class ShortCache {
private ShortCache(){}

static final Short cache[] = new Short[-(-128) + 127 + 1];

static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}


经过比较我们发现,Integer的自动装箱池的最大值并不是一直是127的,当integerCacheHighPropValue不为空的时候,最大值是由integerCacheHighPropValue决定的。我们来看看integerCacheHighPropValue的是在哪儿被赋值的:

private static String integerCacheHighPropValue;

static void getAndRemoveCacheProperties() {
if (!sun.misc.VM.isBooted()) {
Properties props = System.getProperties();
integerCacheHighPropValue =
(String)props.remove("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null)
System.setProperties(props);  // remove from system props
}
}


这段代码告诉我们,integerCacheHighPropValue是通过读取系统配置获得的,也就是说Integer的自动装箱池的大小是可以配置的。我们来看看

getAndRemoveCacheProperties方法的注释就一目了然了。


我们可以在虚拟机参数里面配置Integer的自动装箱池的大小。我们来验证一下。

默认配置时,




结果:


修改虚拟机参数:


结果:


我们修改Integer的自动装箱池的大小为256。所以第二个输出的结果为true。由于第四个输出仍为false,所以我们还可以推断:修改虚拟机的AutoBoxCacheMax的大小只会影响Integer,而不会影响其他包装类。为什么其他包装类不跟Integer一样设计成可配置的呢?这就不得而知了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐