Skip to content

Commit

Permalink
Implement basic automatic attachment/detachment of c++ threads to JVM.
Browse files Browse the repository at this point in the history
No side effects if not enabled
Compile with -DEXPERIMENTAL_AUTO_CPP_THREAD_ATTACH to enable
Requires a compiler with C++11 support
Borrows code/idea from dropbox#372 (comment)
  • Loading branch information
mjmacleod committed Sep 12, 2018
1 parent d547548 commit 5a95938
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion support-lib/jni/djinni_support.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,17 @@ void jniShutdown() {
JNIEnv * jniGetThreadEnv() {
assert(g_cachedJVM);
JNIEnv * env = nullptr;
const jint get_res = g_cachedJVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
#ifdef EXPERIMENTAL_AUTO_CPP_THREAD_ATTACH
jint get_res = g_cachedJVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
if (get_res == JNI_EDETACHED) {
get_res = g_cachedJVM->AttachCurrentThread(&env, nullptr);
thread_local struct DetachOnExit {
~DetachOnExit() {
g_cachedJVM->DetachCurrentThread();
}
} detachOnExit;
}
#endif
if (get_res != 0 || !env) {
// :(
std::abort();
Expand Down

0 comments on commit 5a95938

Please sign in to comment.