温州设计集团网站建设互联网搜索引擎
包装类的缓存问题
1. 概述
嗨,大家好,
【Java 面试合集】
每日一题又来了。今天我们分享的内容是:包装类的缓存问题
。
我们下面的案例以Integer
为例
2. 表现
public class TestCache {public static void main(String[] args) {Integer i = 127;Integer j = 127;System.out.println(i == j); // trueInteger n = 128;Integer m = 128;System.out.println(n == m); // false}
}
大家可以看下上述的实例,每个组合中赋值的内容都是相同的,但是结果是:一个true,一个是false。
这到底是为什么呢??? 本篇文章就带大家看下Integer
缓存问题
3. 分析
valueOf 方法
其实通过下面的方法就可以看到,如果传递的值在某个范围内,就会从if中缓存获取值,那么接下来让我们看看low
, high
, IntegerCache.cache
到底是啥
public static Integer valueOf(int i) {// 判断是否在缓存的范围内if (i >= IntegerCache.low && i <= IntegerCache.high)// 从缓存中获取值return IntegerCache.cache[i + (-IntegerCache.low)];// 如果不在范围内 直接new新的值return new Integer(i);
}
IntegerCache 类实现
通过下面的代码我们可以看到,如果在不额外配置的情况下,我们的取值范围在-128 >= i && i <= 127
。
意思是如果value值是-128 >= i && i <= 127
范围内,会直接获取缓存的值,反之就是会new一个新的对象。
然后我们看下上述的实例,value是127的时候正好是这个范围内,所以无论获取多少次值,都是同一个对象。但是超过这个范围就不一定了
private static class IntegerCache {// 表示最小值static final int low = -128;// 表示缓存访问最大值static final int high;// 缓存对象static final Integer cache[];static {// 默认的缓存池的最大值int h = 127;// 从配置中获取最大值String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");// 判断是否为nullif (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue);// 取最大值i = Math.max(i, 127);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;// 默认的最大值是127 - (-128) + 1 = 256cache = 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() {}
}
4. 问答
4.1 问题1
- 问:两个new Integer 128相等吗?
- 答:不。因为Integer缓存池默认是-128-127
4. 2 问题2
- 问:可以修改Integer缓存池范围吗?如何修改?
- 答:可以。使用-Djava.lang.Integer.IntegerCache.high=300设置Integer缓存池大小
4.3 问题3
- 问:Integer缓存机制使用了哪种设计模式?
- 答:亨元模式;
4.4 问题4
- 问:Integer是如何获取你设置的缓存池大小?
- 答:sun.misc.VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”);
4.5 问题5
- 问:sun.misc.VM.getSavedProperty和System.getProperty有啥区别?
- 答:唯一的区别是,System.getProperty只能获取非内部的配置信息;例如java.lang.Integer.IntegerCache.high、sun.zip.disableMemoryMapping、sun.java.launcher.diag、sun.cds.enableSharedLookupCache等不能获取,这些只能使用sun.misc.VM.getSavedProperty获取