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 没有缓存数据,毕竟是小数,能存的数太多了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论