diff options
author | Sven Gothel <[email protected]> | 2020-02-05 07:24:23 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2020-02-05 07:24:23 +0100 |
commit | 6ef564e5874ce96f12e5d70df4e126b15fb01a29 (patch) | |
tree | b85c7e84729188fd17bfefea201ea979c16030c0 | |
parent | 91c74a4dbad9974d1c0be62e9700986438bb546e (diff) |
JNIEnvContainer::attach/detach: Reuse GetEnv's JNIEnv if available and don't detach GetEnv's JNIEnv.connector-1.5connector_b_1.5
-rw-r--r-- | java/jni/JNIMem.cxx | 32 | ||||
-rw-r--r-- | java/jni/JNIMem.hpp | 1 |
2 files changed, 27 insertions, 6 deletions
diff --git a/java/jni/JNIMem.cxx b/java/jni/JNIMem.cxx index f13a8c85..9861995c 100644 --- a/java/jni/JNIMem.cxx +++ b/java/jni/JNIMem.cxx @@ -28,6 +28,7 @@ JavaVM* vm; thread_local JNIEnvContainer jni_env; jint JNI_OnLoad(JavaVM *initVM, void *reserved) { + (void)reserved; // warning vm = initVM; return JNI_VERSION_1_8; } @@ -49,18 +50,37 @@ JNIEnvContainer::~JNIEnvContainer() { } void JNIEnvContainer::attach() { - if (env != nullptr) + if (env != nullptr) { return; - jint err = vm->AttachCurrentThreadAsDaemon((void **)&env, NULL); - if (err != JNI_OK) - throw std::runtime_error("Attach to VM failed"); + } + JNIEnv *newEnv = nullptr; + int envRes; + + envRes = vm->GetEnv((void **) &env, JNI_VERSION_1_8) ; + if( JNI_EDETACHED == envRes ) { + envRes = vm->AttachCurrentThreadAsDaemon((void**) &newEnv, NULL); + if( JNI_OK != envRes ) { + throw std::runtime_error("Attach to VM failed"); + } + env = newEnv; + } else if( JNI_OK != envRes ) { + throw std::runtime_error("GetEnv of VM failed"); + } + if (env==NULL) { + throw std::runtime_error("GetEnv of VM is NULL"); + } + needsDetach = NULL != newEnv; } void JNIEnvContainer::detach() { - if (env == nullptr) + if (env == nullptr) { return; - vm->DetachCurrentThread(); + } + if( needsDetach ) { + vm->DetachCurrentThread(); + } env = nullptr; + needsDetach = false; } JNIGlobalRef::JNIGlobalRef(jobject object) { diff --git a/java/jni/JNIMem.hpp b/java/jni/JNIMem.hpp index d4e0e33d..389a9157 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 needsDetach = false; public: /* Attaches this thread to the JVM if it is not already attached */ |