title: JNI - Returning a jobject created in native function and used by another native function
body: <p>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.</p>
  
  <p>Here's a simple example:</p>
  
  <pre><code>jobject getAJObject(JNIEnv* jni) {
      jobject obj = jni-&gt;CallStaticVoidMethod(...); // java method that returns a jobject
      return obj;
  }
  
  void func(JNIEnv* jni) {
      jobject obj = getAJObject(jni);
      // Code that uses obj
      ...
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>This article indicates that this code is not safe:
  <a href="http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/index.jsp?topic=%2Fcom.ibm.java.doc.diagnostics.142j9%2Fhtml%2Fhandlocref.html" rel="nofollow">http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/index.jsp?topic=%2Fcom.ibm.java.doc.diagnostics.142j9%2Fhtml%2Fhandlocref.html</a></p>
  
  <p>However I still see examples of JNI code that do exactly this!  Was hoping for some more clarification. </p>