Integer的缓存策略理解

首先先看一个关于Integer的简单代码:

    public static void main(String[] args) {

        Integer int1 = 120;
        Integer int2 = 120;

        Integer int3 = 180;
        Integer int4 = 180;

        System.out.println(int1 == int2);
        System.out.println(int3 == int4);
        
    }

运行结果如下:

true
false

       通过上面的简单例子来说Integer的缓存。

       为了节省内存和提高性能,在Java5就为Integer引入一个新特性。Integer对象杂内部实现中通过使用相同的对象引用实现了重用和缓存。Integer的默认缓存整数区间-128到127。这种缓存策略仅在自动装箱(AutoBoxing)时使用,使用构造创建的Integer对象是不能够被缓存的。自动装箱,即Java编辑器会把原始类型自动转换为封装的的过程,这相当于在调用valueOf()。

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

注意:策略默认的整数区间可以通过启动应用的虚拟机参数修改:-XX:AutoBoxCacheMax=size

通过IntegerCache可以看到,若-128 <= i <= 127,则使用了缓存策略。若不在该范围内,就new一个新的Integer对象。

下面,我们在看一下,IntegerCache的源码,

    private static class IntegerCache {
        //缓存下界(-128),不可更改
        static final int low = -128;
        //缓存上界,暂时设置为null
        static final int high;
        //缓存的整型数组
        static final Integer cache[];

        static {
            // high value may be configured by property
            //缓存上界,可以通过JVM参数来配置,在文中我们有提到过
            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)
            // 范围[-128,127]
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

        IntegerCache类在第一次使用Integer类时被初始化。通过一个for循环初始化了一个拥有256个Integer对象的数组供我们使用。默认范围是[-128 , 127],127可以通过修改JVM启动参数-XX:AutoBoxCacheMax=size进行调整。这种方式通过使用相同的对象引用来实现缓存和复用,以此来节省内存和提高性能。

       当然,这种缓存行为不仅适用于Integer对象。我们针对所有整数类型的类都有类似的缓存机制。

1)Byte

    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

    private static class ByteCache {
        private ByteCache(){}

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

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

2) Short

    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

    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));
        }
    }

3) Long

    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

    private static class LongCache {
        private LongCache(){}

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

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

4) Character

    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }

    private static class CharacterCache {
        private CharacterCache(){}

        static final Character cache[] = new Character[127 + 1];

        static {
            for (int i = 0; i < cache.length; i++)
                cache[i] = new Character((char)i);
        }
    }

       Byte,Short,Long 有固定范围: -128 到 127。对于 Character, 范围是 0 到 127。除了 Integer 可以通过参数改变范围外,其它的都不行。

       另外,插播一句题外话,64位的long,在操作的时候,可以分成两步,每次对32位操作,不是原子操作,但是若使用volatile修饰long和double,那么其读写都是原子操作。(double也是如此)

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值