Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JNIEnv::FindClass: do I need to free the returned jclass reference?

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.

like image 943
P45 Imminent Avatar asked May 19 '14 15:05

P45 Imminent


2 Answers

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:

  • A native method accesses a large Java object, thereby creating a local reference to the Java object. The native method then performs additional computation before returning to the caller. The local reference to the large Java object will prevent the object from being garbage collected, even if the object is no longer used in the remainder of the computation.
  • A native method creates a large number of local references, although not all of them are used at the same time. Since the VM needs a certain amount of space to keep track of a local reference, creating too many local references may cause the system to run out of memory. For example, a native method loops through a large array of objects, retrieves the elements as local references, and operates on one element at each iteration. After each iteration, the programmer no longer needs the local reference to the array element.
like image 115
Thomas Perl Avatar answered Sep 23 '22 21:09

Thomas Perl


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.

like image 33
mkaes Avatar answered Sep 25 '22 21:09

mkaes