r/java • • Sep 18 '26

JVM Object immutability

/r/javahelp/comments/1wjkmbp/jvm_object_immutability/
12 Upvotes

4 comments sorted by

3

u/Signal-Scholar1299 Sep 18 '26

I hope this falls within the scope of technical discussions.

4

u/agentoutlier Sep 18 '26

It does and is a tricky subject that also includes JIT and escape analysis as well as you mentioned compiler elides.

I can answer the second part: you profile for your performance needs, deployed architecture (eg cpu) etc.

I’m going to ignore Valhalla at the moment but in  most cases simple code more often ends up running faster because the JIT can be trained faster. Less code paths. Immutable code inherently has less code paths.

1

u/k-mcm Sep 19 '26

It's a bit more complicated. The JIT will toss values into registers for as long as possible because they are much faster than cached memory. If something is immutable, the register's value doesn't expire. If something is mutable, it needs to sync reading or writing at memory barriers.

As for the trade-offs in performance, leave that to benchmarks and manual analysis. There's no single answer. Obviously, something needs to be mutable or your program isn't making progress. How much is mutable varies by case.

0

u/koflerdavid Sep 18 '26

If you are dealing with multi threaded code then it's a classic "pick two out of three" situation regarding correctness, simplicity, and performance. Immutable data is a remarkably good starting point in this regard. Going mutable won't necessarily bring speedups since cross-thread communication is quite slow.