title: Java ShutdownHook Unable to Join Main Thread when Run From JNI
body: <p>I have some Java code to create a shutdown hook in order to exit cleanly when the client presses ctrl+C:</p>
  
  <pre><code>private static void shutdownHandler(Thread mainThread) {
      try {
          mainThread.join(30000);
      } catch (InterruptedException e) {
      }
  }
  
  public static void main(String[] args) {
      final Thread mainThread = Thread.currentThread();
      Thread shutdownThread = new Thread(() -&gt; shutdownHandler(mainThread));
      Runtime.getRuntime().addShutdownHook(shutdownThread);
  }
  </code></pre>
  
  <p>When I run this from the command line, it works as expected (the main thread exits and returns almost immediately to the command prompt).  However, if I write a JNI wrapper that calls this using the following C++ code instead:</p>
  
  <pre><code>JavaVMInitArgs vm_args;
  // Populate vm_args
  
  JavaVM *jvm;
  JNIEnv *env;
  JNI_CreateJavaVM(&amp;jvm, reinterpret_cast&lt;void**&gt;(&amp;env), &amp;vm_args);
  
  jclass mainClass = env-&gt;FindClass("path/to/my/class");
  jmethod mainMethod = env-&gt;GetStaticMethodID(mainClass, "main", "([L" STRING_CLASS ";)V");
  
  jclass stringClass = env-&gt;FindClass(STRING_CLASS);
  jobjectArray mainArgs = env-&gt;NewObjectArray(0, stringClass, NULL);
  
  env-&gt;CallStaticVoidMethod(mainClass, mainMethod, mainArgs);
  jvm-&gt;DestroyJavaVM();
  </code></pre>
  
  <p>Then the <code>shutdownHandler</code> method hangs until the 30 second timeout elapses, then returns control to the C++ code and eventually exits.  Does anyone know of a way to allow the <code>shutdownHandler</code> method to join the main thread when started from a JNI call?</p>