title: Why I should not reuse a jclass and/or jmethodID in JNI?
body: <p>This is a question related to <a href="https://stackoverflow.com/questions/2088171/jni-bus-error-after-moving-object-creation-to-another-method">a previous post</a>, but this post was solved and now I wanted to change the direction of the question.</p>
  
  <p>When working with JNI, it is necessary to ask the <code>JNIEnv</code> object for <code>jclass</code> and <code>jmethodID</code> for each class and method that will be used in the C/C++ code. Just to be clear, I want to call Java contructors or methods from C/C++.</p>
  
  <p>Since the communication from Java to C/C++ (and viceversa) is costly, I initially thought that one way to minimize this was to reuse the <code>jclass</code> and <code>jmethodID</code>. Therefore, I saved this instances in global variables as follows:</p>
  
  <pre><code>jclass    someClass  = NULL;
  jmethodID someMethod = NULL;
  
  JNIEXPORT jobject JNICALL Java_example_method1(JNIEnv *env, jobject jobj) {
      // initialize someClass and someMethod if they are NULL
      // use someClass and someMethod to call java (for example, thru NewObject)
  }
  
  JNIEXPORT jobject JNICALL Java_example_method2(JNIEnv *env, jobject jobj) {
      // initialize someClass and someMethod if they are NULL
      // use someClass and someMethod to call java again
  }
  </code></pre>
  
  <p>A more specific (and useful) example, which I use to throw exceptions from anywhere in my JNI functions:</p>
  
  <pre><code>jclass    jniExceptionClass           = NULL;
  
  void throwJavaException(JNIEnv *env, const char* msg) {
      if (!jniExceptionClass) {
          jniExceptionClass = env-&gt;FindClass("example/JNIRuntimeException");
      }
      if (jniExceptionClass)
          env-&gt;ThrowNew(jniExceptionClass, msg);
      }
  }
  </code></pre>
  
  <p>The problem is that I continued to use this <em>pattern</em> and got a segmentation fault that was only solved by not-reusing this variables (this was the solution to the previous post).</p>
  
  <p>The questions are:</p>
  
  <ul>
  <li>Why is it illegal to reuse the <code>jclass</code> and <code>jmethodID</code> thru different JNI functions? I thought that this values were always the same.</li>
  <li>Just for curiosity: what is the impact/overhead of initializing all necessary <code>jclass</code> and <code>jmethodID</code> for each JNI function?</li>
  </ul>