From 217781e8322d26f9d1b31aacbd62579dc78269d4 Mon Sep 17 00:00:00 2001 From: Petre Eftime Date: Wed, 6 Jul 2016 15:40:38 +0300 Subject: java: Refactor JNIMem classes Signed-off-by: Petre Eftime --- java/jni/JNIMem.hpp | 68 ++++++++++++++++++++++------------------------------- 1 file changed, 28 insertions(+), 40 deletions(-) (limited to 'java/jni/JNIMem.hpp') diff --git a/java/jni/JNIMem.hpp b/java/jni/JNIMem.hpp index e72c49c..d4e0e33 100644 --- a/java/jni/JNIMem.hpp +++ b/java/jni/JNIMem.hpp @@ -28,62 +28,50 @@ extern JavaVM* vm; + +/* + * This class provides a lifetime-managed JNIEnv object, which attaches or + * detaches the current thread from the JVM automatically + */ class JNIEnvContainer { private: JNIEnv *env = nullptr; public: - JNIEnv *operator*() { - attach(); - return env; - } - - JNIEnv *operator->() { - attach(); - return env; - } - - JNIEnvContainer() { - } - - ~JNIEnvContainer() { - detach(); - } + /* Attaches this thread to the JVM if it is not already attached */ + JNIEnvContainer(); + /* Detaches this thread to the JVM if it is attached */ + ~JNIEnvContainer(); - void attach() { - if (env != nullptr) - return; - jint err = vm->AttachCurrentThreadAsDaemon((void **)&env, NULL); - if (err != JNI_OK) - throw std::runtime_error("Attach to VM failed"); - } + /* Provides access to the local thread's JNIEnv object */ + JNIEnv *operator*(); + /* Provides access to the local thread's JNIEnv object's methods */ + JNIEnv *operator->(); - void detach() { - if (env == nullptr) - return; - vm->DetachCurrentThread(); - env = nullptr; - } + /* Attaches this thread to the JVM if it is not already attached */ + void attach(); + /* Detaches this thread to the JVM if it is attached */ + void detach(); }; +/* Each thread has a local jni_env variable of JNIEnvContainer type */ extern thread_local JNIEnvContainer jni_env; +/* + * This class provides a lifetime-managed GlobalRef variable, which is automatically + * deleted when it goes out of scope. + */ class JNIGlobalRef { private: jobject object; public: - - JNIGlobalRef(jobject object) { - this->object = jni_env->NewGlobalRef(object); - } - - ~JNIGlobalRef() { - jni_env->DeleteGlobalRef(object); - } + /* Creates a GlobalRef from an object passed to it */ + JNIGlobalRef(jobject object); + /* Deletes the stored GlobalRef */ + ~JNIGlobalRef(); - jobject operator*() { - return object; - } + /* Provides access to the stored GlobalRef */ + jobject operator*(); }; -- cgit v1.2.3