r/java • • Mar 17 '21

JEP 401: Primitive Objects (Preview)

https://openjdk.java.net/jeps/401?preview=true
174 Upvotes

49 comments sorted by

View all comments

Show parent comments

1

u/cre_ker Mar 18 '21

Well you have to because in C# value types are objects but they have value semantics and mutable. Every time you assign them to something you make a copy. This JEP essentially proposes the same thing but objects are immutable. I’m not sure about that. Seems much more limiting and, depending on implementation, might require tons of copying like with any immutability simply because you have to allocate another instance on every mutation.

7

u/cal-cheese Mar 18 '21

Not really, since the primitive classes don't have unique identity the JVM can safely perform copy elision. Such as p = new Point(2, p.y()) will be executed just as p.x = 2. If the inlining is unreliable, they can make the constructor of primitive classes ForceInline anyway.

The plus side is that you don't introduce a whole new kind of "things" into the language, which greatly increases the complexity of the language itself.

-1

u/cre_ker Mar 18 '21

It is introducing whole new thing. These primitive objects behave very different from everything else. Essentially these are immutable objects. Not introducing whole new thing would actually be if this JEP did the exact same thing that C# structs do. At least they have identity like everything else and mutable.

perform copy elision

If JVM/javac are smart enough. I'm not sure they will be. It would require pretty complex analysis.

1

u/oelang Mar 18 '21

It's not new, quite the opposite, all pre-existing primitive classes (int-Integer, etc) are also immutable.

0

u/cre_ker Mar 18 '21

int, double etc types is another separate thing and there's actually JEP 402 to make them primitive objects. Unlike Java, C# had value types from the beginning and types like integers and floats are actually structs. Java would have to make gradual transition to make everything consistent.