Integer中缓存池讲解

文章目录

一、简介

Integer缓存池是一种优化技术,用于提高整数对象的重用和性能。在Java中,对于整数值在 -128 到 127 之间的整数对象,会被放入缓存池中,以便重复使用。这是因为在这个范围内的整数值被频繁使用,因此重用这些对象可以节省内存和提高性能。当使用自动装箱机制创建整数对象时,如果对象的值在缓存池范围内,会直接返回缓存池中的对象,而不是创建新的对象。这个特性可以通过调用Integer.valueOf(int)方法来实现。

根据通过设置JVM-XX:AutoBoxCacheMax=可以来修改缓存的最大值,最小值改不了

二、实现原理

底层实现的原理是int 在自动装箱的时候会调用IntegervalueOf进而用到了 IntegerCache。

java 复制代码
    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

没有太多复杂的步骤,只需要判断给定的值是否在指定范围内,如果是的话,则从 IntegerCache 中获取已经预先初始化好的缓存值。

这些缓存值在静态块中被初始化。

java 复制代码
/**
     * 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() {}
    }

这里还有一个有趣的面试题,即在 Integer 类中,数值在 127 以内的两个 Integer 对象会被认为是相等的,而超过 127 的数值则不相等。这是因为在 Java 中,对于数值在 -128 到 127 之间的整型对象,会使用 IntegerCache 中预先初始化的对象。因此,当数值在该范围内时,它们实际上是同一个对象,因此相等性比较会返回 true。这种行为不仅适用于 Integer 类,也适用于 Long 类。

java 复制代码
    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);
    }

对于小数类型的 Float 和 Double,不会有像整数类型那样的缓存机制。因为小数类型的数值范围非常广泛,无法事先预先缓存所有可能的数值。因此,对于 Float 和 Double 类型的对象,相等性比较会根据它们的实际数值来判断,而不是基于对象的引用。所以,即使两个 Float 或两个 Double 对象的数值相同,它们也不会被认为是相等的。

三、修改缓存范围

通过注释可知缓存值可以修改

验证:默认情况下

添加JVM参数 -XX:AutoBoxCacheMax=500

再次执行:


发现i1和i2相等返回true,说明参数生效了。

相关推荐
专注API从业者22 分钟前
Open Claw 京东商品监控选品实战:一键抓取、实时监控、高效选品
java·服务器·数据库
摇滚侠39 分钟前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
keep one's resolveY1 小时前
SpringBoot实现重试机制的四种方案
java·spring boot·后端
天空属于哈夫克32 小时前
企业微信API常见的错误和解决方案
java·数据库·企业微信
摇滚侠2 小时前
VMvare 虚拟机 Oracle19c 安装步骤,远程连接 Oracle19c,百度网盘安装包
java·oracle
梁萌2 小时前
idea报错找不到XX包的解决方法
java·intellij-idea·启动报错·缺少包
Agent产品评测局3 小时前
生产排期与MES/ERP系统打通,实操方法详解 —— 2026企业级智能体自动化选型与实战指南
java·运维·人工智能·ai·chatgpt·自动化
阿丰资源3 小时前
基于Spring Boot的电影城管理系统(直接运行)
java·spring boot·后端
呱牛do it3 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 8)
java
消失的旧时光-19434 小时前
Spring Boot 工程化进阶:统一返回 + 全局异常 + AOP 通用工具包
java·spring boot·后端·aop·自定义注解