java - 为什么整数类缓存值在 -128 到 127 范围内?

标签 java caching

关于我之前的问题,Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128? ,我们知道 Integer class 有一个缓存,它存储 -128127 之间的值。

只是想知道,为什么介于 -128 和 127 之间?

Integer.valueOf() documentation声明它缓存频繁请求的值。但是 -128127 之间的值是否经常被真实请求?我认为经常要求的值是非常主观的。
这背后有什么可能的原因吗?

从文档中还指出:..并且可能会缓存此范围之外的其他值。
这是如何实现的?

最佳答案

只是想知道,为什么介于 -128 和 127 之间?

可以缓存更大范围的整数,但至少必须缓存介于 -128 和 127 之间的整数 ,因为 Java Language Specification 要求这样做。 (强调我的):

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

此要求的基本原理在同一段落中进行了解释:

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. [...]

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.


如何缓存此范围之外的其他值?

您可以使用 -XX:AutoBoxCacheMax JVM 选项,available Hotspot JVM Options 列表中并未真正记录.然而它在 the comments inside the Integer class around line 590 中被提及:

The size of the cache may be controlled by the -XX:AutoBoxCacheMax=<size> option.

请注意,这是特定于实现的,可能在其他 JVM 上可用,也可能不可用。

关于java - 为什么整数类缓存值在 -128 到 127 范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20897020/

相关文章:

java - 如何抑制嵌套集合的Jackson类型信息?

java - 我的 gradle 多项目 + java + groovy + clover + sonarqube 无法在 Sonar 中达到 100% 代码覆盖率

用于 map 的 Java 8 流收集器,误导性分组错误

caching - 将环境状态显式附加到 SCons Builder 依赖项 MD5 指纹

caching - Golang 多模板缓存

java - 重铸一个继承的领域

java - 如何将大型文本文件的数据排序为多维数组?

python - 在 Python 中清除所有 lru_cache

c++ - std::bind 与 lambda 性能

javascript - Turbolinks、Rails、后退按钮、其他来源的页脚