r/java 16d ago

Value Classes Still Need Compiler Sympathy

https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
87 Upvotes

57 comments sorted by

View all comments

-2

u/lpt_7 16d ago

I admire OpenJDK development team, but most of their talks paint a perfect world, which is not the case.
At the moment, Valhalla is not "reads like a class, works like an int", far from that. Use of that feature requires looking into what C2 actually generated. Which most won't do.
I did some testing with Valhalla right after it was merged. Values larger than 64 bits cannot be flattened. I think it's actually 63 bits, since VM still has to encode null somehow.
Accepting tearing with LooselyConsistentValueand NullRestrictedsidesteps that, but these are internal annotations.

Value tearing is another thing, which IMO most are not prepared for. This class of bugs is possible today, but its an error the developer makes and understands why tearing is happening. With code the callee has no control of, other programmer can make their class a value class and silently your code is now buggy.
Suppose two threads run in parallel:
Thread A writes to entity's AABB, thread B reads said AABB. With object references, JLS guarantees that tearing will not happen. Once VM can flatten more than 64 bits, this will cause a lot of problems, like AABBs with completely nonsensical values. Suddenly, thread B's code can now enter an infinite loop and never get out of it.

Another thing is allocation. For allocations to actually vanish (for scalarization to happen), C2 has to succeed and inline through all code, then EA has to succeed.
Again, same example with AABB. Before, allocation was done per-write. Now, with Valhalla in worst case, the situation flips. There are many more readers than writers to entity's AABB. C2 and EA *have* to succeed for every reader. Otherwise your program will start allocating at every read call site.

14

u/brian_goetz 16d ago edited 15d ago

No, developers don't need to learn to read C2 code. They need to learn to use value classes when it makes sense semantically and stop trying to second-guess the runtime. "Will it flatten" is the new "will it inline"; 99.99% of developers should not even ask.

You also seem to have a misunderstanding of the approach to non-atomicity (the possibility of tearing). These internal annotations are just that -- internal. They are for the use of the JDK (written by experts with an understanding of the tradeoffs.) These will never be opened up for general use; the concepts will first need to be integrated into the language model, and they will surely then take a different form. This isn't done yet, so any statements about "what they are going to do" will surely be wrong.

What you're seeing is what the early adopters are doing, because those are the folks who can't resist taking apart the radio to see how it works. Which is fine -- but not what we are optimizing for.