Java基础-数据类型缓存解析

文章目录
  1. 1. 基本类型缓存解析
    1. 1.1. Integer缓存解析
    2. 1.2. Long及Byte、Character缓存解析

基本类型缓存解析

Integer缓存解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}

public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

1、使用自动装箱(Integer i = 1)方式创建Integer对象时,会使用valueOf进行Integer对象的初始化,此时,会调用IntegerCache.high,这是需要对IntegerCache这个静态内部类进行初始化。


2、IntegerCache类中有一个cache数组,在加载IntegerCache的时候,会将-128到127的Integer对象都创建了,并存到cache数组中,然后在判断当前初始化的Integer对象的值是否在-128到127之间,如果是,就直接从cache缓存中取,如果不存在,则new一个新的Integer对象。


3、之后再使用自动装箱的方式创建Integer对象时,值在-128到127之间时会直接从cache缓存中取。

所以,使用自动装箱的方式创建的Integer对象,两者进行比较时,只要其值相等就是ture。而不在-128到127之间的,比较时会新new一个对象,而导致比较结果为false


注意:Integer的最低值是固定的,只能是-128,而最高值是可以通过jvm参数设置的。在执行java程序的时候加上-XX:AutoBoxCacheMax=参数即可。

Long及Byte、Character缓存解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}

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);
}

Long的缓存机制(LongCache)与Integer的类似,还有Character(CharacterCache),Byte(ByteCache)的缓存机制也是类似。不过只有Integer的最大值可以通过jvm参数设置,其他的都固定的。其中,Byte,Short,Long 的范围: -128 到 127;Character, 范围是 0 到 127。


关注我的微信公众号:FramePower
我会不定期发布相关技术积累,欢迎对技术有追求、志同道合的朋友加入,一起学习成长!


微信公众号

如果文章对你有帮助,欢迎点击上方按钮打赏作者