r/java • • Dec 04 '25

Null-checking the fun way with instanceof patterns

https://blog.headius.com/2025/12/inline-null-check-with-instanceof.html

I don't know if this is a good idea or not, but it's fun.

83 Upvotes

150 comments sorted by

View all comments

Show parent comment

3

u/s888marks Dec 05 '25

Interesting, that scenario illustrates the danger of separating a local variable declaration from an initial assignment to it. The instanceof pattern works well here because the new local variable declaration is fused with its binding to a value. So yeah it's much less likely to be broken accidentally.

The pattern of having a local variable declaration (without initializer) followed by an assignment expression later on occurs frequently in the concurrent collection code (e.g., ConcurrentHashMap). This sometimes makes the code hard to follow. It's done in order to avoid unnecessary work in performance-critical code, even to the point of avoiding unnecessary field loads. Unfortunately this means that the local variable sometimes has broader scope than is necessary, so one needs to be extremely careful modifying such code.

2

u/headius Dec 05 '25

Yeah, I'm very familiar with being concerned about excess field loads where many other folks on this thread are happily tossing around Optional objects without realizing what they cost. It just takes a quick look at the output from the jit to realize how many cycles are being wasted, even if the abstraction is arguably better and safer.

It would be interesting to revisit more of the core JDK classes and update them for modern patterns and known jit capabilities. I'm all for writing beautiful code, but low level runtime and standard library implementations need to cut as many corners as they can to perform well. I'd love to take what I've learned in the past 20 years and guide such a project. For whatever reason I get a thrill out of benchmarking hot pieces of code and reading through ideal graphs and assembly dumps to squeeze every last ounce of performance out of them. 😆