包装类缓存

Java包装类缓存

为什么需要包装类?

  Java是面向对象开发,通过基本数据类型对应的包装类可以获得更多的api操作。并且现在很多数据端采用对象来对接。

本文主要以Integer为主进行解释

1. 示例

 public static void main(String[] args) {
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        System.out.println(i1 == i2);  // false

        Integer i3 = 10;
        Integer i4 = 10;
        System.out.println(i3 == i4); // true

        Integer i5 = 200;
        Integer i6 = 200;
        System.out.println(i5 == i6); // false
    }

 2. 内部缓存类解析

  i3、i4实现了自动装箱,实际上调用了Integer的valueOf()方法

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

 

//内部缓存类
private
static class IntegerCache { static final int low = -128; //缓存下界
    //high可以配置,通过 VM 参数-XX:AutoBoxCacheMax=<size
        static final int high;
        static final Integer cache[]; //缓存实质上是一个存放Integer的数组
      //静态代码块,Integer类加载时就缓存
        static {
            // high value may be configured by property
            int h = 127;//默认127
            String integerCacheHighPropValue =
          //读取VM配置参数 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127);//上限最小值是127 // Maximum array size is Integer.MAX_VALUE 最大值是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;//保证[-128,127]在缓存范围内 } private IntegerCache() {} }

 

posted @ 2020-03-18 14:49  Qmillet  阅读(230)  评论(0)    收藏  举报