Integer 的缓存机制
Integer 类有一个特殊的缓存机制,是 Java 语言规范(JLS)要求的自动装箱特性的一部分
Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. The cache is initialized on first usage. The size of the cache may be controlled by the -XX:AutoBoxCacheMax=
option. During VM initialization, java. lang. Integer. IntegerCache. high property may be set and saved in the private system properties in the jdk. internal. misc. VM class. WARNING: The cache is archived with CDS and reloaded from the shared archive at runtime. The archived cache (Integer[]) and Integer objects reside in the closed archive heap regions. Care should be taken when changing the implementation and the cache array should not be assigned with new Integer object(s) after initialization.
package io.github.charlie;
/**
* @author Charlie Zhang
* @version v1.0
* @date 05/05/2025
* @description Integer 的缓存
*/
public class IntegerDemo {
public static void main(String[] args) {
// 示例代码
Integer a = 10; // 实际调用Integer.valueOf(10)
Integer b = 10;
Integer c = Integer._valueOf_(10);
System._out_.println(a == b); // 输出true,因为使用了缓存对象
System._out_.println(a == c); // 输出true,因为使用了缓存对象
}
}

@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache._low _&& i <= IntegerCache._high_)
return IntegerCache._cache_[i + (-IntegerCache._low_)];
return new Integer(i);
}


浙公网安备 33010602011771号