Video in progress

Your services call native libraries through JNI or FFM, and every now and then the whole JVM crashes. What architectural decisions do you make for stability?

Native code is outside the JVM's protection: an error in it isn't an exception, it is the death of the whole process. I put the native part behind a minimal, verifiable boundary, move it to a separate process if possible, grant permission explicitly with --enable-native-access, and prepare diagnostics and automatic recovery for crashes.

📖 Answer

An NPE in Java code breaks one request. A bad pointer in a native library is a SIGSEGV: all requests, all threads, the cache, everything is gone. In the hs_err file there is a C [libimage.so+0x1a2b3] frame.

  1. Narrow the boundary. Hide the native API behind one module/class. Check every argument on the Java side (length, null, range), so untrusted data never goes straight into native code. In FFM, the bounds checking of MemorySegment is safer than manual pointer arithmetic in JNI, so for new code I choose FFM over JNI.

  2. Process isolation. If the native code is untrusted or lightly tested (image/video codecs, old C libraries), I move it to a separate process: a sidecar or a worker pool, over gRPC or stdin/stdout. If it crashes, only the worker dies and is brought back up. The cost is serialization and latency, but the blast radius shrinks sharply.

  3. Explicit permission. From JDK 24 even using JNI gives a warning. In the base image I grant permission with an explicit module name like --enable-native-access=com.acme.imaging, so I know which code touches native and I'm ready for a future deny default.

  4. Resource management. Native memory isn't visible in NMT and the GC doesn't know about it. An explicit close() / Arena for every native allocation, a counter metric at the library level, and a separate share in the container memory budget.

  5. Crash diagnostics. -XX:ErrorFile on a persistent volume, a core dump policy, native builds with debug symbols. An alert on crash frequency.

  6. Testing. Fuzzing and a build with AddressSanitizer for the native part. It is the only reliable way to find these bugs before they reach prod.

My usual decision: if the library has a pure Java alternative, I often choose it even if it is 2-3 times slower. Stability and ease of diagnosis are worth more than speed.