Global Reference in JNI is said to be a reference that has to be manually freed by the programmer. It has nothing to do with the c context. so a code like :
{
jclass clsStr = (*env)->NewGlobalRef(env,cls);
}
return clsStr;
will give an error saying that clsStr is undefined / undeclared. I understand this. But what i don’t understand is the use of these type of references.
What is global about clsStr in the above code ? How this variable can be useful in future or after the call returns ? I also read that “Basically, the global reference is useful for ensuring that it (and its contents) will survive to the next JNI invocation” but i don’t understand this.
It means that you’re allowed to hold on to the reference you get from
NewGlobalRef()across multiple calls to the native mathod. The reference will remain valid until you explicitly callDeleteGlobalRef().This is in contrast to local references:
If you store a global reference in a variable that’s allowed to go out of scope before you call
DeleteGlobalRef(), you leak memory. The following is an example of that: