Integer的缓存策略理解

本文深入探讨Java中Integer缓存机制,解释自动装箱时如何利用缓存提高性能,及如何通过JVM参数调整缓存范围。同时,对比了不同整数类型如Byte、Short、Long和Character的缓存策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先先看一个关于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也是如此)

 

 

回答: 这个错误是由于浏览器的CORS策略引起的。CORS是一种安全机制,用于限制请求。当浏览器发现请求的源与目标不在同一个时,会发送一个预检请求,检查目标服务器是否允许请求。如果目标服务器没有正确配置CORS头部,浏览器就会拒绝该请求,从而导致这个错误。\[1\]\[2\] 对于你提到的具体错误,'file:///D:/vue/vue-first/data.json'是一个本地文件路径,而'null'是请求的源。由于这是一个本地文件请求,而不是通过HTTP协议请求,所以CORS策略不适用于这种情况。因此,你可以通过将数据文件放在与你的应用程序相同的中,或者使用服务器来提供数据,以避免这个错误。 #### 引用[.reference_title] - *1* [Access to XMLHttpRequest athttp://xxx‘ from originhttp://xxx‘ has been blocked by CORS ...](https://blog.csdn.net/qq_41470439/article/details/109361842)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [前后端分离问题Access to XMLHttpRequest athttp://localhos...has been blocked by CORS policy: ...](https://blog.csdn.net/qq_42416602/article/details/121731774)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Access to XMLHttpRequest athttp://xx‘ from originhttp://xx‘ has been blocked by CORS policy](https://blog.csdn.net/weixin_51603038/article/details/129319187)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值