I have some Java code to create a shutdown hook in order to exit cleanly when the client presses ctrl+C:
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(() -> shutdownHandler(mainThread));
Runtime.getRuntime().addShutdownHook(shutdownThread);
}
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:
JavaVMInitArgs vm_args;
// Populate vm_args
JavaVM *jvm;
JNIEnv *env;
JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args);
jclass mainClass = env->FindClass("path/to/my/class");
jmethod mainMethod = env->GetStaticMethodID(mainClass, "main", "([L" STRING_CLASS ";)V");
jclass stringClass = env->FindClass(STRING_CLASS);
jobjectArray mainArgs = env->NewObjectArray(0, stringClass, NULL);
env->CallStaticVoidMethod(mainClass, mainMethod, mainArgs);
jvm->DestroyJavaVM();
Then the shutdownHandler
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 shutdownHandler
method to join the main thread when started from a JNI call?