Java Integer 类与 IntegerCache 机制剖析
Integer 类概述
Integer 是 Java 中 int 基本类型的包装类(wrapper class),属于 java.lang 包。主要功能包括:
- 提供对象表示形式,便于在集合中使用
- 提供丰富的工具方法(如字符串转换、进制转换等)
- 实现自动装箱(autoboxing)和拆箱(unboxing)
IntegerCache 机制详解
设计目的
解决整数包装类频繁创建的问题,通过缓存常用范围内的 Integer 对象:
- 减少内存占用:避免重复创建相同值的对象
- 提高性能:减少对象创建和垃圾回收开销
- 优化比较操作:使 == 在缓存范围内可正确比较值
实现原理
在 Integer 类内部有一个静态内部类 IntegerCache:
private static class IntegerCache {
static final int low = –128;
static final int high;
static final Integer cache[];
static {
// 默认上限值
int h = 127;
// 可通过JVM参数调整上限
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty(\”java.lang.Integer.IntegerCache.high\”);
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
h =
评论前必须登录!
注册