计算机科学与技术 开题报告 网站建设,Wordpress托管 点点,网站建设客户调研表,晋中建设网站包装类的缓存问题1. 概述 嗨#xff0c;大家好#xff0c;【Java 面试合集】每日一题又来了。今天我们分享的内容是#xff1a;包装类的缓存问题。 我们下面的案例以Integer 为例 2. 表现
public class TestCache {public static void main(String[] args) {Integer i 127…包装类的缓存问题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.high300设置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获取