A neat JVM trick:

By the spec, dereferencing null has to throw a NullPointerException. So the JVM has to explicitly check for null on every access, right?

It doesn't, in a pretty amazing way.
When the JVM compiles the byte code to machine code, it elides this check. So when the code actually tries to dereference a null object, it will trigger a SIGSEGV, just like a C program would do.
Now unlike a C program, the JVM will catch this SIGSEGV, look at the instruction that caused the segfault, restore control flow, and generate and throw a NullPointerException.
So this makes the happy path fast. But segfaults are incredibly slow, and if this null access is frequent, it'd a lot slower than the explicit null checks, wouldn't it?

Yes. And if this happens, the JVM will recompile the corresponding method at runtime.
You don't have to like #Java; but I think seriously believe the JVM is one of the finest pieces of software engineering.
You can follow @urhein.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.