Java Integer的缓存策略

1.首先是在valueOf()中出现了对缓存策略的使用,通过IntegerCache可知当-128<=i<=127(默认)时候使用了缓存策略。也就是i在范围内的话就从内存中取出返回,如果不在范围内就new一个Integer对象。

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

2.IntegerCache是Integer的一个静态内部类:
1)如果设置了java.lang.IntegerCache.high,就使用这个值,如果没有设置就使用127,java.lang.IntegerCache.high这个值是通过JVM参数改变的,在java程序执行的时候加上 -XX:AutoBoxCacheMax=<size> 的参数即可。
2)使用了断言assert;
3)其实所谓的在内存中取值,就是在数组中,可以看出,Integer的值是被存在了cache数组中的。

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() {}
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 先看一段代码: 输出结果为: 这是为何呢?在 Java 5 中,为 Integer 的操作引入了一个新的特性,用来...
    Q南南南Q阅读 2,141评论 0 5
  • 以下内容为作者辛苦原创,版权归作者所有,如转载演绎请在“光变”微信公众号留言申请,转载文章请在开始处显著标明出处。...
    光变阅读 1,807评论 3 6
  • 本文将介绍Java中Integer的缓存相关知识。这是在Java 5中引入的一个有助于节省内存、提高性能的功能。首...
    编程鸭阅读 298评论 0 0
  • 本文将介绍Java中Integer的缓存相关知识。这是在Java 5中引入的一个有助于节省内存、提高性能的功能。首...
    墨雨轩夏阅读 571评论 0 10
  • 吾好美腿,阅腿无数,心有八字,品评优劣,私藏多年,今日共享。 先总八字:“白嫩光洁,浑圆修长”。次做分类:前四字论...
    绝对疯了阅读 377评论 0 0

友情链接更多精彩内容