还记得被多个对象的判断==
/equals
支配的恐惧吗?
随便来一个,
public static void main(String[] args) {
Integer i = 12; //1
Integer i1 = 12; //2
Integer i2 = 129; //3
Integer i3 = 129; //4
System.out.println(i == i1); // 5
System.out.println(i2 == i3); //6
}
这个的输出结果是什么呢?
直接展示答案吧,输出结果是:
true
false
我们来研究一下为什么.
首先我们要知道,在1.5之后的JDK为我们提供了自动装箱与拆箱,用来解决8中基本类型->对象的转换问题,这一点如果不是很清楚了话可以先google了解一下.
上面代码中的语句1-4无疑都是发生了装箱的,那么我们反编译一下这段代码,来看一下在装箱过程中到底发生了什么.
在命令行中执行以下命令:
javac IntegerTest.java
javap -v -c -s -l IntegerTest
可以看到输出结果如下:
可以看到自动装箱的时候调用的是Integer.valueOf()
方法,那么我们看一下他的实现:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当传入的数字在某个范围(这个范围默认是-128到127)之间时,直接返回缓存的一个列表,找一下缓存列表的初始化的地方:
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() {}
}
这是IntegerCache
缓存类的实现,在类加载的时候用静态方法快进行了初始化,将缓存范围内的值预先加载好放在数组中.
可以看到对缓存范围的上限数字是通过读取配置来设置的,因此,Integer的缓存范围是可以通过参数 -XX:AutoBoxCacheMax=size
来设置的.
这种缓存行为不仅适用于Integer对象。针对所有整数类型的类都有类似的缓存机制。
而通过参数设置缓存范围,只有Integer可以.其他的都不允许.
2019-05-10 完成
以上皆为个人所思所得,如有错误欢迎评论区指正。
欢迎转载,烦请署名并保留原文链接。
联系邮箱:huyanshi2580@gmail.com
更多学习笔记见个人博客——>呼延十
var gitment = new Gitment({ id: 'Java中的常量类缓存机制', // 可选。默认为 location.href owner: 'hublanker', repo: 'blog', oauth: { client_id: '2297651c181f632a31db', client_secret: 'a62f60d8da404586acc965a2ba6a6da9f053703b', }, }) gitment.render('container')