JNI Global Reference Leaks: The Unfreed Native Allocations

One of the most insidious native memory leaks arises from JNI code failing to release native memory allocated via `malloc` or `NewGlobalRef` without a corresponding `free` or `DeleteGlobalRef`, leading to persistent memory consumption outside the JVM's garbage collector's purview.

The top 3

  1. Top 3 Scenarios Causing JNI Global Reference Leaks: The most common culprits include forgetting to call `DeleteGlobalRef` (especially in error paths or callbacks), caching local references directly without proper global reference conversion and deletion, and persistent JNI global references preventing `ClassLoader` unloading in modular applications.
  2. Essential Tools for JNI Global Reference Leak Detection: Effective diagnosis relies on tools like heap dump analyzers (e.g., Eclipse MAT, JProfiler) to visualize GC roots, the JVM's Native Memory Tracking (NMT) for native memory insights, and runtime checks such as `-Xcheck:jni` (or Android's CheckJNI) to flag incorrect JNI usage.
  3. Top 3 Best Practices to Prevent JNI Global Reference Leaks: Crucial coding patterns include explicitly calling `DeleteGlobalRef` for every `NewGlobalRef`, avoiding global references for short-lived objects, and leveraging weak global references for cache-like scenarios to allow garbage collection.

Sources

Open the full topic