JNI Local Reference Free Time

Viewed 73

According to The Official Documentation Says:

Local references are valid for the duration of a native method call, and are automatically freed after the native method returns

Imaging a case, We have a native framework a.so

And we load it.

static JavaVM * g_cachedJVM;

CJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM * jvm, void * /*reserved*/) {

    g_cachedJVM = jvm;
    return JNI_VERSION_1_6;
}

And we call a native method implement by a.so, we start a c++ timer in this method.

CJNIEXPORT jobject JNICALL Java_A_Custom_Method(JNIEnv* jniEnv, jobject /*this*/) {
   startTimerInCurrentTheadWithoutBlockCurrentThread(Seconds(1),[](){
       //invoke method every 1 second
       cppMethod();
   });
}

void cppMethod() {
    //Create some jni local reference use g_cachedJVM
    // what is the life cycle of the local reference?
}

Question: what is the life cycle of the local reference in the cpp method

1 Answers

Since your cppMethod is a native method you need handle local references by yourself.
Technically your local references will be bound to JNIEnv and older versions of the jvm did release all references when their Envwas removed.
But I am not aware that this behaviour is somewhere specified.

So to anwer your question:

  1. All local references you create will be bound to the JNIEnv that you created
  2. If you do not release your local references they will remain valid for ever.

Therefore is is usually best to always handle your local references, although it is not needed in JNI calls.
You can make this handling simpler with a RAII wrapper around PushLocalFrame/PopLocalFrame

Related