包装类型的缓存机制

包装类型的缓存机制

Java 基本数据类型的包装类型的大部分都用到了缓存机制来提升性能。

Byte,Short,Integer,Long 这 4 种包装类默认创建了数值 [-128,127] 的相应类型的缓存数据,Character 创建了数值在 [0,127] 范围的缓存数据,Boolean 直接返回 TRUE or FALSE

对于 Integer,可以通过 JVM 参数 -XX:AutoBoxCacheMax=<size> 修改缓存上限,但不能修改下限 -128。实际使用时,并不建议设置过大的值,避免浪费内存,甚至是 OOM。

对于Byte,Short,Long ,Character 没有类似 -XX:AutoBoxCacheMax 参数可以修改,因此缓存范围是固定的,无法通过 JVM 参数调整。Boolean 则直接返回预定义的 TRUEFALSE 实例,没有缓存范围的概念。

Integer 缓存源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
// IntegerCache.cache 是一个静态数组,里面预先存好了 -128 到 127 的 Integer 实例。
// i + 128 是因为数组下标从 0 开始:i = -128 时,下标 = 0; i = 127 时,下标 = 255
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

// 私有静态内部类
private static class IntegerCache {
static final int low = -128;
static final int high;
static {
// high value may be configured by property
int h = 127;
}
}

示例:

1
2
3
4
5
6
7
8
9
10
11
public class CacheDemo {
public static void main(String[] args) {
Integer a = 126;
Integer b = 126;
Integer c = 128;
Integer d = 128;

System.out.println(a == b); // true 缓存命中
System.out.println(c == d); // false 超出缓存范围
}
}
  • ab 指向同一对象,==true
  • cd 超出缓存范围,各自 new 了对象,==false

包装类型缓存机制 ⇒小范围的数值对象被预先创建并复用

这样做节省内存和提高效率,但比较时仍推荐使用equals(),以避免因缓存范围不同带来的“==”误判。


包装类型的缓存机制
https://hxxyy.info/2025/09/23/包装类型的缓存机制/
作者
HXXYY
发布于
2025年9月23日
许可协议