Should JLS 5.1.7 require that boxing uses `valueOf`?
some-java-user-99206970363698485155 at vodafonemail.de
some-java-user-99206970363698485155 at vodafonemail.de
Mon Mar 18 21:41:24 UTC 2024
Thanks a lot for all your answers, especially for this in-depth compiler
and JIT view on it!
My previous message and the subject might have diverted this discussion
in the wrong direction: The main problem I see with the JLS section
5.1.7 in its current form is that it does not seem to be very useful.
And I assumed the only way to make it useful would be to require using
`valueOf`, but maybe there are other ways as well.
The problem is that if you were to strictly follow the JLS, then there
are two caching implementations:
-"JLS cached": Implicit boxing of constant expressions in certain ranges
(e.g. -128 to 127) to same instances
-"valueOf cached": Guarantees provided by `valueOf`methods
These two caching implementations can be identical (i.e. a compiler uses
`valueOf`for boxing), but there is no guarantee for it.
If one would now want to write a `List<Byte>`which contains 'canonical'
boxed values they would have to write rather contrived code to be JLS
compliant:
-implementation using "JLS cached" values:
```
void add(byte b) {
// Canonicalize to "JLS cached" values, which only applies for
constants
Byte boxed = switch (b) {
0 -> (Byte) (byte) 0;
1 -> (Byte) (byte) 1;
2 -> ...
}
list.add(boxed);
}
```
-implementation using "valueOf cached" values:
```
void addZero() {
// Must explicitly use `Byte.valueOf` even if IDEs and static code
// analysis tools say it can be omitted
Byte boxed = Byte.valueOf(0);
list.add(boxed);
}
```
In reality this might not matter much because most (if not all)
compilers use `valueOf`for implicit boxing, and as you said Project
Valhalla might render this obsolete in the future. But the current
situation is not ideal if Java programs accidentally rely on compiler
implementation details assuming that implicit boxing uses `valueOf`.
(Though I am not sure how many programs really do perform identity
checks on boxed primitived.)
Regarding over-specifying: Of course the JLS should try to not be too
specific. But that raises the question if that part of JLS section 5.1.7
about boxed instance identity is useful at all.
More information about the discuss
mailing list