欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Java的Integer缓存池

Java的Integer缓存池

2025/2/4 5:27:48 来源:https://blog.csdn.net/weixin_73093777/article/details/145398065  浏览:    关键词: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 propertyint 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_VALUEh= 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 cachereturn 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 没有缓存数据,毕竟是小数,能存的数太多了

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com