Skip to content
This repository has been archived by the owner on Jan 4, 2023. It is now read-only.

JNIMem: Do not detach Java threads to avoid segfault when JVM terminates #153

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions java/jni/JNIMem.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions java/jni/JNIMem.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down