Suppose I have this code in a JNI function that implements a native
function stub:
JNIEnv* env; /*This is set to a valid JNIEnv* for this thread*/
jclass clz = env->FindClass("foo"); /*this has worked*/
Do I need to call
env->DeleteLocalRef(clz);
once I'm done with it? I'm not returning clz
back to Java so I'm thinking that I need to delete the local reference? It seems a little odd though since like a MethodID
, a jclass
doesn't contain an object instance.
It is never wrong to call DeleteLocalRef
, so you should always call it, otherwise you could run into situations where the number of local references is used up.
When your JNI code is called from Java, and it's short-running, you might be lucky enough that the local references get cleaned up for you after you return to the Java caller, but if you e.g. call into the Java VM from native code (so there's no "outer" Java VM frame from which your JNI code is called), then you will quickly use up your local variables, because they will never be deleted by a non-existent Java caller.
To quote the official Java documentation:
In most cases, the programmer should rely on the VM to free all local references after the native method returns. However, there are times when the programmer should explicitly free a local reference. Consider, for example, the following situations:
No you don't need to call DeleteLocalRef
.FindClass
returns a local reference. So there is no need to delete. The JVM will do this automatically after the JNI call is finished.
But if you want you can delete the local reference. It should not make any difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With