Java的Integer缓存池

Java的Integer缓冲池?

Integer 缓存池主要为了提升性能和节省内存。根据实践发现大部分的数据操作都集中在值比较小的范围,因此缓存这些对象可以减少内存分配和垃圾回收的负担,提升性能。

在-128到 127范围内的 Integer 对象会被缓存和复用。

原理

int 在自动装箱的时候会调用Integer.valueOf,进而用到了 IntegerCache。

复制代码
@HotSpotIntrinsicCandidate
public static Integer value0f(int i){
    if(i>= IntegerCache.low && i<= IntegerCache.high)  //如果传入的int值在缓存范围内,则直接从缓存中返回Integer对象
        return IntegerCache.cache[i+(-IntegerCache.low)];
    return new Integer(i);                              //否则,创建新的Integer对象
}
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 = VM.getSavedProperty( key:"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 i = low;
        for(int k=0;k< cache.length; k++)    //遍历创建-128-127的所有对象
            cache[k]= new Integer(i++);
        assert IntegerCache.high >= 127;
    }
    
    private IntegerCache(){}
}

所以这里还有个面试题:就是为啥 Integer 127 之内的相等,而超过 127 的就不等了?

  • 因为小于等于127的 Integer 对象是从同一个缓存池中获取的,它们指向的是相同的对象实例,所以它们的引用相等

不仅 Integer 有,Long 同样有一个缓存池,不过范围是写死的 -128 到 127,不能通过JVM参数进行调整

复制代码
@HotSpotIntrinsicCandidate
public static Long value0f(long l){
    final int offset = 128;
    if(l>= -128 &&l<= 127){ // will cache
        return LongCache.cache[(int)l + offsetl];
    }
    return new Long(l);
}

总结

  • Byte,Short,Integer,Long这4种包装类默认创建了数值[-128,127]的相应类型的缓存数据

  • Character 创建了数值在 [0,127]范围的缓存数据

  • Boolean 直接返回 True or False

  • Float 和 Double 没有缓存数据,毕竟是小数,能存的数太多了

相关推荐
爱装代码的小瓶子2 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
YuTaoShao2 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
源码_V_saaskw3 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
Maybe_ch3 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨3 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王3 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
双力臂4044 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试
Edingbrugh.南空4 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
CodeCraft Studio5 小时前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html
QQ_4376643145 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++