Skip to content

Instantly share code, notes, and snippets.

@latkin
Last active January 21, 2023 21:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save latkin/4a11ac2edb502c4a9141 to your computer and use it in GitHub Desktop.
Save latkin/4a11ac2edb502c4a9141 to your computer and use it in GitHub Desktop.
JNI Object Lifetimes Quick Reference
JNI Object Use across JNI calls? Use on different thread? Notes
JavaVM Yes Yes To obtain an instance of JavaVM, either:
  • Expose a native export jint JNI_OnLoad(JavaVM* vm, void* reserved), which will be invoked when LoadLibrary is called from Java
  • Call pJNIEnv->GetJavaVM(&pJavaVM) on a valid JNIEnv
You don't need to clean up a JavaVM.
JNIEnv Yes No A JNIEnv is valid across JNI calls, but only on its original thread. If you are going to cache a JNIEnv, consider using a thread_local or similar.

If a JNIEnv is not available for the current thread (e.g. within a native callback), one can be obtained by calling pJavaVM->AttachCurrentThread(&pJNIEnv, null). In this case you are responsible for cleaning up with pJavaVM->DetachCurrentThread().

Otherwise, you don't need to clean up a JNIEnv.

Primitive value types

jboolean, jchar, jshort, jfloat, jdouble, jsize, jint, jlong, jbyte

Yes Yes These are just aliases for normal native value types, so there are no special lifetime or cleanup considerations.
Reference types

jobject, jclass, jthrowable, jstring, jarray, jbooleanArray, jbyteArray, jcharArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray, jobjectarray

No (local refs) No (local refs) If one of these is passed in as an argument to a JNI call, or returned from another JNI API, it is typically a local reference and is only valid for the duration of that JNI call, on that same thread. These do not require any cleanup.

A durable global reference can be created from any local reference by calling globalJThing = (jthing) pJNIEnv->NewGlobalRef(localJThing). Global references are valid across JNI calls and on any thread. Global references must be cleaned up with pJNIEnv->DeleteGlobalRef(globalJThing).

Yes (global refs) Yes (global refs)
ID types

jfieldID, jmethodID

Yes Yes These are durable and can be used without restriction. No cleanup is required.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment