title: JNI - correctly attach/detach threads
body: <p>I have this code:</p>
  
  <pre><code>JNIEXPORT void package_MyAPI_callback(JNIEnv *env, jobject thiz, jobject caller) {
      JavaVM *vm;
      env-&gt;GetJavaVM(&amp;vm);
      jclass callbackClass = (jclass) env-&gt;NewGlobalRef(env-&gt;FindClass("package/TimeLoadedListenerUIThread"));
      jobject cachedCaller = (jobject) env-&gt;NewGlobalRef(caller);
      jmethodID javaCallback = env-&gt;GetMethodID(callbackClass, "onTimeLoaded", "(Z)V");
  
      CppSetCallback([=] {
          JNIEnv *bgEnv;
          vm-&gt;AttachCurrentThread(&amp;bgEnv, NULL);        
          bgEnv-&gt;CallVoidMethod(cachedCaller, javaCallback, false);
  
          bgEnv-&gt;DeleteGlobalRef(callbackClass);
          bgEnv-&gt;DeleteGlobalRef(cachedCaller);
          //vm-&gt;DetachCurrentThread();
      });
  }
  </code></pre>
  
  <p>And somewhere in Kotlin code:</p>
  
  <pre><code>override fun onTimeLoaded(resetToCurrentTime: Boolean) {
      activity.runOnUiThread { 
          activity.updateTimeSelector(resetToCurrentTime) }
      }
  }
  </code></pre>
  
  <p><code>CppSetCallback</code> sets callback (as functional) to internal core of app.  There, the functional  is called from <code>std::thread</code>. </p>
  
  <p>This code runs, but I am not sure if it is correct, because If I call <code>vm-&gt;DetachCurrentThread();</code> app crashes. How should I call detach, or when?</p>