aboutsummaryrefslogtreecommitdiffstats
path: root/java
diff options
context:
space:
mode:
authorSven Gothel <[email protected]>2020-02-05 07:24:23 +0100
committerSven Gothel <[email protected]>2020-02-05 07:24:23 +0100
commitdf57187a03c5801d4bbd2fb1bb1b0f87cc62bb3c (patch)
tree313517928c12ca28add30f8e77369d0b55890f44 /java
parente140e0ab0f4beec333fdc39a8a62704195032139 (diff)
JNIEnvContainer::attach/detach: Reuse GetEnv's JNIEnv if available and don't detach GetEnv's JNIEnv.
Diffstat (limited to 'java')
-rw-r--r--java/jni/JNIMem.cxx32
-rw-r--r--java/jni/JNIMem.hpp1
2 files changed, 27 insertions, 6 deletions
diff --git a/java/jni/JNIMem.cxx b/java/jni/JNIMem.cxx
index f13a8c8..9861995 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 d4e0e33..389a915 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 */