Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

常量池技术 超出[-128,127] ,会重新创建新的对象实例,那会把这个实例缓存起来吗? #461

Closed
jol5 opened this issue Sep 4, 2019 · 2 comments
Labels
help wanted Extra attention is needed

Comments

@jol5
Copy link

jol5 commented Sep 4, 2019

Java 基本类型的包装类的大部分都实现了常量池技术,即 Byte,Short,Integer,Long,Character,Boolean;这 5 种包装类默认创建了数值[-128,127] 的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。

如:
Integer one=333;
Integer two=333;

在创建one,是不是不会把对应的结果缓存起来啊?这才导致 one != two;
问:表面上时不会缓存的,那为什么不缓存呢?如果不缓存,为什么又要预先创建[-128,127] 呢?

@jinyahuan
Copy link
Contributor

jinyahuan commented Sep 12, 2019

首先要了解为什么Integer a=1走缓存,而Integer b=333不走缓存:

  1. 自动拆装箱(看字节码就知道了,最终调用的是 valueOf 方法,而这个方法在一定范围内时是走缓存的)。

然后就是为啥要走缓存:

  1. 性能方面。see Integer#valueOfas this method is likely to yield significantly better space and time performance by caching frequently requested values

最后是为把啥缓存设置为[-128,127]区间:

  1. 技术规范。JLS7 5.1.7If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p . It is always the case that a == b .
  2. 性能和资源之间的权衡(当然也可以调整缓存的正向最大值,自己看 IntegerCache 类的实现)。

@Snailclimb Snailclimb added the help wanted Extra attention is needed label Sep 16, 2019
@miozus
Copy link

miozus commented Sep 2, 2021

我认为可能的原因还有,一个 byte 的存储范围刚好是 - 128~127 ,好传输和操作;(Char类型,负数 asc 码不能表示,所以是非负数)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

4 participants