I'm wondering how safe it is to use a local reference created in a native method and returned by that method to the caller.
Here's a simple example:
jobject getAJObject(JNIEnv* jni) {
jobject obj = jni->CallStaticVoidMethod(...); // java method that returns a jobject
return obj;
}
void func(JNIEnv* jni) {
jobject obj = getAJObject(jni);
// Code that uses obj
...
}
I have tested this code and it does work fine, but I'm worried that it's not safe. My understanding from reading the JNI spec is local references are only valid in the stack frame it was created, and are cleaned up when the native method returns. Does this mean that obj can get garbage collected after getAJObject finishes, and while still on the native side without returning back to java?
This article indicates that this code is not safe: http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/index.jsp?topic=%2Fcom.ibm.java.doc.diagnostics.142j9%2Fhtml%2Fhandlocref.html
However I still see examples of JNI code that do exactly this! Was hoping for some more clarification.