当前位置: 首页 > article >正文

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 没有缓存数据,毕竟是小数,能存的数太多了


http://www.kler.cn/a/527130.html

相关文章:

  • C++,STL 命名空间:理解 std 的作用、规范与陷阱
  • 【微服务与分布式实践】探索 Eureka
  • 商品列表及商品详情展示
  • C# 9.0记录类型:解锁开发效率的魔法密码
  • Vue.js组件开发-实现全屏平滑移动、自适应图片全屏滑动切换
  • (笔记+作业)书生大模型实战营春节卷王班---L0G2000 Python 基础知识
  • Pdf to forms如何实现?如何在3分钟内将PDF自动转换为Microsoft Forms
  • labelme_json_to_dataset ValueError: path is on mount ‘D:‘,start on C
  • 《苍穹外卖》项目学习记录-Day7缓存菜品
  • pytorch图神经网络处理图结构数据
  • Git进阶之旅:分支管理策略
  • 【华为OD-E卷 - 字符串化繁为简 100分(python、java、c++、js、c)】
  • 计算机网络一点事(23)
  • minimind - 从零开始训练小型语言模型
  • 树莓派入门笔记(二)最常用的树莓派 Linux 命令及说明_树莓派系统命令
  • PostgreSQL TRUNCATE TABLE 操作详解
  • AVL搜索树
  • 商品列表及商品详情展示
  • 通过想像,见证奇迹
  • 【gRPC-gateway】初探grpc网关,插件安装,默认实现,go案例
  • Mysql进阶学习
  • 最新 Android 热门开源项目公布
  • 稀疏混合专家架构语言模型(MoE)
  • 【4Day创客实践入门教程】Day4 迈向高手之路——进一步学习!
  • .cc扩展名是什么语言?C语言必须用.c为扩展名吗?主流编程语言扩展名?Java为什么不能用全数字的文件名?
  • 七、深入了解SpringBoot的配置文件