享元模式源码分析
2019-07-31 本文已影响0人
别拿爱情当饭吃
JDK源码分析
Integer
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
//IntegerCache重点
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 =
//可以在jvm中设置最大值,可设置的范围是(127-Integer.MAX_VALUE之间 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
- Integer可设置最大值:127~Integer.MAX_VALUE
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);
}
private static class LongCache {
private LongCache(){}
//缓存范围是:-128~127;不可在jvm中改变缓存范围的最大值
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
- Long的缓存范围是:-128~127
Character
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
//缓存范围是0~127
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}
- Character的缓存范围是:0~127
Byte
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
//范围是:-128~127
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
}
- Byte的缓存范围是:-128~127
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);
}
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
//-128~127
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
- Short的缓存范围是:-128~127
总结
- 整形才有缓存范围:比如Byte,Short,Character,Integer,Long。
- 浮点型没缓存范围:比如Float,Double