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.
The top 3
- Neglected `DeleteGlobalRef()` Calls: The most direct cause of JNI global reference leaks is failing to explicitly call `DeleteGlobalRef()` when a global reference is no longer needed, as these references are not automatically garbage collected by the JVM.
- Persistent Caching Without Cleanup: Developers often create global references to cache `jclass` or `jmethodID` objects for performance across multiple native calls; however, if these cached references are never released when the native component or application exits, they become permanent leaks.
- High-Volume Iterative Operations: In scenarios involving frequent JNI calls within loops, such as processing large arrays or continuous data streams, repeatedly creating global references without periodic `DeleteGlobalRef()` calls can quickly exhaust the JVM's global reference table, leading to crashes.
Sources
Open the full topic