diff --git a/java/jni/JNIMem.cxx b/java/jni/JNIMem.cxx index f13a8c85..e2c760f4 100644 --- a/java/jni/JNIMem.cxx +++ b/java/jni/JNIMem.cxx @@ -51,15 +51,28 @@ JNIEnvContainer::~JNIEnvContainer() { void JNIEnvContainer::attach() { if (env != nullptr) return; - jint err = vm->AttachCurrentThreadAsDaemon((void **)&env, NULL); - if (err != JNI_OK) + + jint ret; + ret = vm->GetEnv((void **)&env, JNI_VERSION_1_8); + if (ret == JNI_OK) { + shouldDetach = false; + return; + } + + ret = vm->AttachCurrentThreadAsDaemon((void **)&env, NULL); + if (ret == JNI_OK) + shouldDetach = true; + else throw std::runtime_error("Attach to VM failed"); } void JNIEnvContainer::detach() { if (env == nullptr) return; - vm->DetachCurrentThread(); + + if (shouldDetach) + vm->DetachCurrentThread(); + env = nullptr; } diff --git a/java/jni/JNIMem.hpp b/java/jni/JNIMem.hpp index d4e0e33d..c4d95693 100644 --- a/java/jni/JNIMem.hpp +++ b/java/jni/JNIMem.hpp @@ -36,6 +36,7 @@ extern JavaVM* vm; class JNIEnvContainer { private: JNIEnv *env = nullptr; + bool shouldDetach = false; public: /* Attaches this thread to the JVM if it is not already attached */