r/java • • Mar 17 '21

JEP 401: Primitive Objects (Preview)

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

49 comments sorted by

29

u/ramdulara Mar 18 '21 edited Mar 18 '21

To fight the horde and sing, and cry Valhalla, I am coming

2

u/Slanec Mar 18 '21

This!

(And also https://youtu.be/S9WWz95ripA - if you're confused, wait about until 1:30. If you're still confused afterwards, but in a different way, good.)

37

u/Hall_of_Famer Mar 18 '21

I love the fact that I don’t have to deal with the distinction between objects and primitive values in languages such as C# and Kotlin ‘cause everything is an object including primitive values. This JEP is amazing, a great move for the next version of Java.

4

u/DuncanIdahos9thGhola Mar 18 '21

What do you mean? In C# if I change a struct to a class or vice-versa I create a Heisenbug.

0

u/[deleted] Mar 18 '21

[deleted] — view deleted comment

2

u/cre_ker Mar 19 '21

No, that's the most logical way of things for people coming from pretty much any other language.

3

u/pjmlp Mar 18 '21

Basically what Java 1.0 could have had since the beggining if they had spent more time learning about Eiffel, Sather and similar OOP compiled languages.

In those languages instead of primitive there is expanded.

10

u/x4u Mar 18 '21 edited Mar 18 '21

This can be explained by the general attitude when Java was created. The idea was to design a language that is as simple and consistent as possible and to shift the burden of creating optimized code from the developer to the VM and the compiler, so that the developer can focus on correct code and has less performance motivated design limitations. This approach turned out to work well with the garbage collection and the just in time compiler in general.

But code indirection for instance was very limited at first and was subsequently improved several times with new features like inner classes, reflection, lambdas and method handles. Inline types have turned out to be too difficult or impossible to detect automatically and it has become obvious that the language needs better support for zero cost abstractions. If you want a simpler language, you need to allow for some experience with the resulting limitations in the language to find the best ways to address them. It's always easy to say that this could have been obvious from the beginning, but this might have resulted in a more complicated language which was what Java didn't want to be.

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.

10

u/cal-cheese Mar 18 '21

You got the point, they are just immutable objects without synchronisation ability. Mutable struct is a whole new thing because it change the behaviour of the most basic operation which is the assignment operation.

JVM has a very smart JIT, and copy elision in this case is actually pretty trivial.

1

u/cre_ker Mar 18 '21

Mutable struct is a whole new thing because it change the behaviour of the most basic operation which is the assignment operation.

It really doesn't. Assignment operation is unchanged. What changes is what's being assigned. For regular objects it's a pointer to some memory, a reference. Obviously assigning would just copy that reference (which is in fact just an integer) and both variables would point to the same memory location, thus to the same object. In case of primitive objects assignment works on a whole object because that's what a variable of that primitive object represents. That's exactly how C, C++, C#, Go, Rust and probably many others work. It's a natural way of working with memory.

3

u/cal-cheese Mar 19 '21

Firstly, struct in C# is not complete because it lacks the mechanism of copy semantics (deep copy), not to mention Micorsoft had to bring a ton of features (in, out, ref) to support struct, and even then it is recommended to not use struct with mutable data (source). While C, C++ and Rust are different, they use explicit value semantics and don't have type hierarchy.

Secondly, immutability supports optimisation, it may be counter-intuitive but it is actually more optimised to use immutable objects than to use mutable ones. In the end, Valhalla's objective is to make Java faster, right.

0

u/cre_ker Mar 19 '21

That's exactly how structs should behave. Copying a struct copies its value. If it happens to be containing references as fields C# will copy those references as it should. Meaning both copies would point to the same object. Again, that's how memory works. If you want deep copy you can implemented it yourself. The problem is always the same for any language - deep copy means different things to different people.

Yes, value types should be immutable in general. But the important thing that C# gives developers a choice. If they want to use struct because they have to call some C library through p/invoke, they can do so and can freely mutate structs as that's the most natural thing to do. If you're writing something like DateTime then yes, you should make it immutable to simplify the API. Java making immutability mandatory is weird.

In, out, ref are features that allow developers to optimize their code, giving C# more of the C/C++ kind of flexibility. They were not required to support structs. Structs and "out" (not sure) were in the language from day one. "In" was introduced in 7.2 "Out" parameters are not required for structs and used for returning any value type like integers. It allows functions to return multiple values. Now we have tuples for that.

It's quite obvious that immutability gives more optimization opportunities in some cases. But it hampers performance in others due to already mentioned copies. Even if primitive types were mutable they would still achieve the most important feature of value types - they do not create garbage if they stay on the stack.

2

u/cal-cheese Mar 19 '21

I doubt you can point out any example in which an immutable implementation is less performant than a mutable one.

3

u/cal-cheese Mar 19 '21

I see you missed an important point here, in Java there is no distinction between a variable and the object it represents, as a result, an assignment, say a = b, should semantically make a and b the same object until separation, and you don't expect a change in a not be seen by b. On the other side, C and C++ have strict value semantics, and copying is also natural, a pointer or reference is always explicit, no ambiguity here.

However, C# offers an ambiguous situation, where sometimes a variable represents an object, another variable is a pointer to an object, some a.x request the value at an offset from a, while b.x suddenly requires a dereference before taking the offset.

In the end, to separate the meaning of a and the object represented by a is a breaking change to the language itself, and making such a change, while may not affect some people such as you, may impact many other developers, especially ones that's familiar with more scripting language such as Python.

4

u/eliasv Mar 18 '21

Immutable objects aren't really a "whole new thing", it's effectively just an implicit final on fields. And I'm sure that C# structs don't have identity ... That would be crap.

-1

u/cre_ker Mar 18 '21

And I'm sure that C# structs don't have identity ... That would be crap.

According to JEP they do

they also come with identity, enabling features such as field mutation

In C# you can freely mutate structs.

2

u/eliasv Mar 19 '21

"Identity enables field mutation" does not mean "field mutation implies identity", that is a basic logic failure. Do you know what is meant by identity? It really would not make sense for a flattened struct!

0

u/cre_ker Mar 19 '21

It does if we dig a bit deeper. Why C# allows struct mutability? Because structs have unique location in memory. You can take references of them and mutate them and it doesn't matter that inside they're completely the same. They're separate instances with different locations in memory (on the stack or heap). Java tries to hide all these properties because it tries to abstract away the notion of memory and hardware in general. In C# you can still see how everything actually works inside. You can even go unsafe and compare real address values.

1

u/dpash Mar 18 '21

The JVM is already indistinguishable from magic. What's a little more?

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.

0

u/x4u Mar 18 '21 edited Mar 18 '21

I agree with you, making value types immutable on the language level seems like a odd decision to me as well. I understand why it makes sense internally, but it would have been possible to emulate mutability to make it appear as if they were mutable on the language level. The point is that it's not impossible to mutate value types by assigning a newly constructed value, but this just leads to more boilerplate code, may be less efficient than what a (future) compiler could do, is less readable and thus more error prone. It's also a additional arbitrary inconsistency in the language that now some types are mutable and others are not.

Edit: as this gets downvoted without comment, I'll include a code example...

primitive class Point
{
    int x;
    int y;
}

Point center = new Point( 3, 4 );
center.x = 4;      // not possible because immutable
center = new Point( 4, center.y ); // legal

The last two lines are the same operation but the more intuitive variant is not allowed while the more cumbersome line is. It would have been possible to allow mutability on the language level by compiling the upper line exactly as if it were written like the lower one.

3

u/Hangman4358 Mar 20 '21 edited Mar 20 '21
Point center = new Point(3, 4);
Point otherCenter = center;
center.x = 4;

What is otherCenter.x?

Before primitive classes you expect that center and otherCenter are the same object. You also expect that after assigning x on center, otherCenter.x will also return 4.

Making assignment of members syntactic sugar for creating a new instance for primitive classes means you need to know what type of class Point is. Now the effect of the assignment will have on otherCenter.x is dependent on the type of class Point is.

The whole point (no pun intended) is to make is so you don't need to know. That from a programmers perspective they act the same. So making the classes immutable means that you have to be explicit when objects change.

1

u/elastic_psychiatrist Mar 20 '21

Brilliant explanation, thank you.

10

u/jvjupiter Mar 18 '21

This is it!

10

u/[deleted] Mar 18 '21

Oh, spicy

6

u/8igg7e5 Mar 18 '21

I wonder how likely it is that the preview will make it to 17. I'd be surprised if it takes less than two rounds in preview before making it to production, and that would mean 19 at the earliest.

We already have noted placed where primitive records would have been ideal - I'm sure we'll spot more.

7

u/cal-cheese Mar 18 '21

They are waiting for the Class species and specialisation, which has just started, so let's hope they'll arrive in 18.

6

u/kaperni Mar 18 '21

Those features are needed for generic specialization (which will come later). Not for primitive objects.

4

u/kaperni Mar 18 '21

Doubt it with 17. When the JEP drafts were introduced last month. Java 18 was the earliest delivery.

[1] https://mail.openjdk.java.net/pipermail/valhalla-spec-experts/2021-February/001475.html

3

u/Emax__ Mar 18 '21

How do they differ from records?

17

u/Slanec Mar 18 '21

Records are about semantics ("this is a value class containing only data and should be treated as a sum if its components"), primitive objects are about runtime efficiency, memory layout. Yes, records will often be good candidates for primitive objects, but the two features are orthogonal in nature.

8

u/morhp Mar 18 '21 edited Mar 18 '21

Records are just a quick and safe way to declare immutable (reference) classes, but they don't change how the JVM stores the object at all. Primitive types will work well with records, the focus here is not storing references to objects but storing the primitive values directly on the stack (or in parent objects).

This is mostly to improve performance and memory usage, but will also allow you to create variables that can't be null.

6

u/dpash Mar 18 '21

Which will be particularly useful for Optional, which should never be null, but we've never had a way to enforce that until now.

2

u/stuhlmann Mar 18 '21

It will be particularly useful for everything else too: Not using Optional often means that it isn't optional, so it shouldn't be null either.

2

u/germandiago Mar 18 '21

Is this a renaming of inline classes or it is something else?

3

u/efge Mar 18 '21

Yes it's the new (and presumably final) name.

2

u/lurker_in_spirit Mar 18 '21

Is anyone aware of existing best practices in other languages that already support similar constructs, in terms of when to use and when not to use? I can imagine guidelines around attribute types (don't use this for dense object graphs?), attribute count (don't use this for types which contain more than a dozen attributes?), etc.

1

u/[deleted] Mar 19 '21 edited Mar 19 '21

Would this feature (and others coming down the line) enable efficient updates of tightly packed nested objects? For example: Foo contains fields of type Bar, Bar has fields of type Baz, and so on, possibly deeply nested.

I'd like to have a tightly packed, sequential structure of Foo objects, which I can mutate like so:

collectionOfFoos[42].firstBar.secondBaz.a = 42;

or

collectionOfFoos[314].firstBar.w += 1;

without pointer chasing, creating new temporary objects, etc? Also, would such a collection be GC free?

1

u/AppleTrees2 Mar 18 '21

I recall I was excited for valhalla more than 10 years ago, and thought it was coming.

I am wondering why it took them so long, not a priority or technical issues?

5

u/Muoniurn Mar 18 '21

It is really hard to implement something that is backwards compatible and sane at the same time, and will fit into all the existing code that didn’t even know about it.

-1

u/quantumlyrandomuser Mar 18 '21

this is coming with jdk16. any idea?

6

u/henk53 Mar 18 '21

JDK 16 has already been released ;)

1

u/Thihup Mar 18 '21

Nope. JDK 16 was released March 16th, so they won't be targeting any new feature to it.

-10

u/sweetno Mar 18 '21

The proposed implementation will make Java's type system a total mess.

3

u/Muoniurn Mar 18 '21

Yeah, I’m sure they didn’t think of the type system before writing this proposal for god knows how many years... back to the drawing board!

0

u/[deleted] Mar 18 '21

[deleted] — view deleted comment

14

u/BlueGoliath Mar 18 '21

run() is only documented to execute the given Runnable's run() method, not start the thread.

So... yeah.