Java装箱==的池化坑

原创作品,出自 “晓风残月xj” 博客,欢迎转载,转载时请务必注明出处(http://blog.csdn.net/xiaofengcanyuexj)。

由于各种原因,可能存在诸多不足,欢迎斧正!

        今天读《Effective Java》,读到“基本类型优于装箱基本类型” ,其中那个Integer例子觉得不合适,于是看了Integer源码,发现还真是有点问题,至少我的jdk1.7是有问题的。

     Java是高度封装基于JVM API的语言,和C++一个重要的区别就是不支持运算符重载。就我肤浅地理解,基本的运算操作+、-、*、/、==等对于开发者老说通常是不透明的,所以对于模糊的地方不好把握,对于装饰器类型也就是通常意思的装箱类型,如下:                                                             

int(4字节) Integer
byte(1字节) Byte
short(2字节) Short
long(8字节) Long
float(4字节) Float
double(8字节) Double
char(2字节) Character
boolean(未定) Boolean


        ==对于装箱类型是不好把握的。以Integer为例,通常在[-128,127](其中127取决于JDK中的)系统变量,具体如下:

 String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 

    由于比较简单,直接上实例代码的

/**
 * @功能: Java测试类
 * @authord: jin.xu
 * @version: v1.0.0
 * @see:
 * @date: 2016/1/30 11:49
 */
public class Test {

    public static void main(String[] args) {
        Integer i=127;
        Integer j=127;

        if(j==i){
            System.out.println("true");
        }else{
            System.out.println("false");
        }


        Integer k=128;
        Integer t=128;
        if(k==t){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

    }
}
输入结果分别是:

true
false

      具体原因应该说是jdk还不能说是JVM将小范围的数值做了缓存,如int的[-128,127](其中128并不是一个比较准确的答案),new对象的时候不是直接在堆上创建,而是从常量池中读取,避免频繁创建对象。我们知道,在堆上创建对象是有系统开销的,而池化技术可以在一定程度上解决这类问题,如内存池、线程池等。当然,像jdk这类直接选定数值的方法也是比较粗糙的,还好其中的integerCacheHighPropValue 变量可以针对不同机器作调整。具体直接贴jdk代码的

 /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * 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.
     */

    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() {}
    }


     所以建议是对于装箱类型,比较数值的时候最好直接使用equal()或者XXXValue()方法,避免使用运算符==。自己踩过或者躲过的坑,希望别人也不要踩。

    

     最近空闲时间有看源代码的习惯,如雅虎基于在线机器学习开源爬虫anthelion和dubbo的






               

  






      

            




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值