Unsafe considered scary…

Khun Yee Fung, Ph.D.
Programming is Life
2 min readFeb 4, 2024

I was reading an article about Unsafe in Java being deprecated.

I did have a run-in with a Java network library a few years ago that was most probably caused by this (it did not look like a JNI error. At least to me). Basically, I was making a once sequential program parallel (to 256 hardware threads). Originally, the program would initiate a HTTP request if something is not present. When I parallelized it, I forgot about this network request.

Then I was reminded about it when I saw the logs, when network requests were queuing up once in a while. But this condition was quite rare, so I just sort of ignored it.

A few weeks later, I started having out-of-memory errors that were not in my program. It seemed a library was crashing the JVM. Eventually I traced it to the network library. Once I replaced it with another library, the OOM exceptions and JVM crashes went away.

I always say I prefer compile-time errors than run-time error. But there is a kind of run-time errors that are worse than some exceptions in some threads that the system might be able to step out and around. Or something. But if the JVM crashes, that is a different story. As looking at the stack trace of a JVM crash report I usually have that unbearable feeling of helplessness.

A Java program should never ever crash the JVM. It is worse than a run-time error when the whole system comes crashing down. No logs, no nothing, just the JVM crash report. It is either my program crashing the JVM, which is not supposed to happen, even when it runs out of memory. Or my program hit a JVM bug, that is not good. It would mean tons of debugging time for me to find out where. And since I can’t replicate the production load realistically (loads are not always created equal), I would have to risk multiple crashes in production before knowing where to look. The third reason is of course a library is crashing the JVM. That might be easy to rectify, or not, depending on the importance of the library.

Anyhow, I was lucky, as the crash report did indicate where the error occurred. I replaced the library, refactored the networking code (all in one place in any case), and I never saw the issue again.

--

--

Khun Yee Fung, Ph.D.
Programming is Life

I am a computer programmer. Programming is a hobby and also part of my job as a CTO. I have been doing it for more than 40 years now.