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.

The top 3

  1. The Absolute Must: Always Pair NewGlobalRef with DeleteGlobalRef: JNI global references are not garbage collected by the JVM; every `NewGlobalRef` call must have a corresponding `DeleteGlobalRef` to prevent persistent Java object leaks and eventual `OutOfMemoryError` exceptions.
  2. Optimize GC with NewWeakGlobalRef for Non-Blocking Object Access: Employ `NewWeakGlobalRef` when a native reference should not prevent the Java object from being garbage collected, but always remember to promote it to a strong reference (e.g., via `NewLocalRef`) before use and explicitly free it with `DeleteWeakGlobalRef` afterwards.
  3. Minimize JNI Global Refs: Let Java Classes Hold Object References: Whenever feasible, avoid creating JNI global references by designing your application so that Java objects hold references to other Java objects, allowing the JVM's automatic garbage collector to manage their lifecycles, thereby reducing native memory leak risks.

Sources

Open the full topic