Java的Integer缓存

tech2022-08-19  78

问题

Integer a = 100, b = 100, c = 150, d = 150; System.out.println(a == b); // true System.out.println(c == d); // false

Integer 缓存了 byte 大小的值在缓冲区, 观察源码

public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) // IntegerCache.low 固定 -128 IntegerCache.high 可配置 默认 127 return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } 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 = sun.misc.VM.getSavedProperty("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 j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }

从上面的代码可以看出 :

Integer 的默认缓存区为-128 ~127 ;缓存区可以配置[ -XX:AutoBoxCacheMax=< size >} 或 Djava.lang.Integer.IntegerCache.high=< value >]最大值,不能配置最小值,最大值必须大于等于127;自动装箱采用的是valueOf方法;直接 new Integer() , 是不经过valueOf方法,不会被缓存。

尝试其他基本类型包装类 Long:

public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); }

特点: 最大值不能被改变 Character:

public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); }

特点: 小于等于127 [0-127] char 一般范围 [0 ,2^16]

Short:

public static Short valueOf(short s) { final int offset = 128; int sAsInt = s; if (sAsInt >= -128 && sAsInt <= 127) { // must cache return ShortCache.cache[sAsInt + offset]; } return new Short(s); }

-128 ~127 不可调节

Byte:

public static Byte valueOf(byte b) { final int offset = 128; return ByteCache.cache[(int)b + offset]; }

不判断 全部缓存 Boolean

public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }

直接返回

浮点数:

public static Float valueOf(float f) { return new Float(f); }

不缓存

总结

Boolean 浮点数不缓存 整数缓存 byte大小数组,Integer 可以调整最大值 Char 缓存 1- 127

最新回复(0)