Java中的包装类缓存

Java中的包装类缓存

最近在网上看到一个有意思的笔试题目,题目是考察Integer类的valueOf(String s),题目如下:

以下四行代码输出的结果依次是什么?
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000")); 
System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); 
System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); 
System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128"));    
System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000"));  

笔主看到这个题目,就想当然的给出了自己的答案。答案如下:

false
false
false
false
false

之所以得出这个错误答案,是因为笔主认为valueOf(String s)每次返回的都是新创建的对象。为了验证自己的答案是否正确,就使用IDE写了这几行代码,运行后得到了如下答案:

System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));   --false
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));    --false
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));   --true
System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128"));   --true   
System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000"));    --false

惊不惊喜,意不意外,想当然给出的答案是错误的!!!笔主这时候内心有了疑惑,为什么结果既有false又有true呢?为什么正确的答案是这样?为了消除内心的疑惑,认真看了Integer类valueOf(String s)的源码,如下:

/**
* 此方法先调用 public static int parseInt(String s, int radix)将String类型转换为int,
* 然后又调用了public static Integer valueOf(int i)方法返回Integer类型对象
*/
 public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
 }

我们需要重点关注下Integer的valueOf(int i)的源码,如下:

/**
* IntegerCache是Integer的私有静态内部类,看这个名字可以猜测到这个类和缓存有关系:
* IntegerCache.low的值是-128
* IntegerCache.high的值是127
* 这个方法的作用就是当-128<=i<=127时,从IntegerCache类的数组中取出一个Integer对象,否则就新创建一个Integer对象。
*/
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
 }

看了这段源码之后,笔主内心的疑惑消除了。题目中-128和127在缓存的范围之内会使用缓存的对象,而-1000、128、1000在范围之外会创建的新的对象,所以才有了false、false、true、true、false这个答案。虽然解决了内心的疑惑,但是有必要好好了解下IntegerCache这个类。了解一个类最快的方法当然是看源码,如下:

/**
  * Cache to support the object identity semantics of autoboxing for values between
  * -128 and 127 (inclusive) as required by JLS.
  * JLS要求通过缓存来支持在-128(包括)和127(包括)之间的数值自动装箱为同一对象。
  *
  * The cache is initialized on first usage.  The size of the cache
  * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
  * During VM initialization, java.lang.Integer.IntegerCache.high property
  * may be set and saved in the private system properties in the
  * sun.misc.VM class.
  *缓存会在第一次使用Integer这个类时被初始化。缓存数组的大小可以被--XX:AutoBoxCacheMax选项控制。在VM初始化时, IntegerCache.high
  *属性可以被设置保存在sun.misc.VM类的私有系统配置中。
  */
private static class IntegerCache {
        static final int low = -128; //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); //取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; //将high的值设置为127

            cache = new Integer[(high - low) + 1]; //创建数组,length=127-(-128)+1=256
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++); //数组的值从-128至127

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

通过IntegerCache类的注释来看,和其他系统属性一样,在JVM启动时,cache数组的大小是可以通过设置-Djava.lang.Integer.IntegerCache.high=xxx传递进来的。
通过这个笔试题目,我们学习到Integer这个类是有缓存的。众所周知,Java中除了Integer还有其他类型的包装类。那么其他类型包装类存在缓存吗?答案是:除了Float和Double,其他包装类也存在缓存。
在包装类中,缓存的基本数据类型值的范围如下:

包装类型基本数据类型缓存范围
Booleanbooleantrue,false
Bytebyte-128~127
Shortshort-128~127
Characterchar0~127
Integerint-128~127
Longlong-128~127
Floatfloat
Doubledouble

Boolean、Byte、Short、Character 、Long类型的缓存原理和Integer类型的相似,源码中均有体现。由于篇幅问题,这里不再逐一赘述。
学习到这里,我们可以总结下:
部分包装类提供了对象的缓存,实现方式是在类初始化时提前创建好会频繁使用的包装类对象,当需要使用某个包装类的对象时,如果该对象包装的值在缓存的范围内,就返回缓存的对象,否则就创建新的对象并返回。

由于笔主水平有限,笔误或者不当之处还请批评指正。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值