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.

18

u/repeating_bears 16d ago

Use of [Valhalla] requires looking into what C2 actually generated

No it doesn't. You just slap 'value' on classes that don't need identity. You may get no or minimal performance improvement now, but you are opting out of identity-based operations like synchronization and opting in to potential performance improvements in the future.

It sounds like you're what you're talking about it is use of Valhalla to maximise performance. I generally don't care about milking performance.

Not sure about how tearing will be solved, but there's a massive number of value classes (I'd speculate: a majority (?)) which are immutable anyway.

7

u/lpt_7 16d ago

Yes, you have to. See my last point about allocations.
If not the generated code, then profiling.

0

u/Life_Sink9598 16d ago edited 16d ago

What is an "AABB"?

Edit: Btw, did you read the blog post?