享元模式在开源代码中的应用
16lz
2021-01-22
享元模式的作用:运用共享技术来有效地支持大量细粒度对象的复用。
案例
享元模式比较经典的应用就是 JDK 中部分基本类型的包装类,缓存了一定数值范围的对象,valueOf 方法转换为包装对象时,如果值在缓存范围内,即返回缓存对象。
- Byte,缓存了 -128 ~ 127
- Short,缓存了 -128 ~ 127
- Character,缓存了 0 ~ 127
- Integer,缓存了 -128 ~ 127,JVM 启动参数 -XX:AutoBoxCacheMax 可以设置范围的最大值
- Long,缓存了 -128 ~ 127
- Boolean,缓存了 true 和 false 对象
不同版本的 JDK 机制不一样,这里说的是 JDK 8。
为啥 Float、Double 没缓存呢?因为计算机可表示的两个整数之间的浮点数太多太多,无法确定使用频率,缓存没有意义。
以 Integer 为例
再看一下 Integer 的静态内部类 IntegerCache,在未设置 java.lang.Integer.IntegerCache.high 时,JVM 加载 IntegerCache 类时,静态方法块缓存了 -128 ~ 127;设置了 high,缓存最大值取 127 与 high 中的较大者。public final class Integer extends Number implements Comparable<Integer> {
public static Integer valueOf(int i) {
//在 IntegerCache 中缓存了 [low,high]
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
}
所以就会出现如下打印情况,原因是等号右边的数值自动装箱,反编译可以看出调用了 valueOf 方法,100 在 IntegerCache 的缓存之内,200 不在缓存中每次都 new 新对象。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 i1 = 100;Integer i2 = 100;Integer i3 = 200;Integer i4 = 200; System.out.println(i1==i2); //打印trueSystem.out.println(i3==i4); //打印false通过缓存对象的方式,共享不可变对象,减少创建,节省内存开销,降低垃圾收集器的负担,减少 GC。↓↓ 查看脑图
更多相关文章
- 帮你解读什么是Redis缓存穿透和缓存雪崩
- Spring Ioc 实例化 Bean 对象有几种方式?
- MyBatis之Mapper XML 文件详解(六)-缓存配置
- Javascript面向对象入门
- redis缓存服务
- HTTP缓存