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

相关推荐
阿珊和她的猫21 分钟前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html
喜欢吃燃面41 分钟前
C++算法竞赛:位运算
开发语言·c++·学习·算法
草莓熊Lotso44 分钟前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
开发语言·c++·经验分享·笔记·其他
水痕0144 分钟前
gin结合minio来做文件存储
java·eureka·gin
谱写秋天1 小时前
Qt 5.5 的安装与配置(使用 VSCode编辑)
开发语言·vscode·qt
项目申报小狂人1 小时前
算法应用上新!自适应更新策略差分进化算法求解球形多飞行器路径规划问题,附完整MATLAB代码
开发语言·算法·matlab
寒士obj1 小时前
Spring事物
java·spring
柯南二号2 小时前
【Java后端】Spring Boot 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
阿珊和她的猫5 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript