保存 JNIEnv* 的最佳方法是什么?
What is the best way to save JNIEnv*
我有一个使用 JNI 的 Android 项目。在实现监听器 class 的 CPP 文件中,有一个回调 x() 。当调用 x() 函数时,我想在 java class 中调用另一个函数。但是,为了调用 java 函数,我需要访问 JNIEnv*。
我知道在回调的同一个cpp文件中,有一个函数:
static jboolean init (JNIEnv* env, jobject obj) {...}
调用init(..)
时是否需要在cpp文件中保存JNIEnv*作为成员变量?并在回调发生时使用它?
抱歉,我是 JNI 的初学者。
缓存 JNIEnv*
不是一个特别好的主意,因为您不能在多个线程中使用相同的 JNIEnv*
,甚至可能无法将它用于多个本机调用同一线程(参见 http://android-developers.blogspot.se/2011/11/jni-local-reference-changes-in-ics.html)
编写一个获取 JNIEnv*
并在必要时将当前线程附加到 VM 的函数并不难:
bool GetJniEnv(JavaVM *vm, JNIEnv **env) {
bool did_attach_thread = false;
*env = nullptr;
// Check if the current thread is attached to the VM
auto get_env_result = vm->GetEnv((void**)env, JNI_VERSION_1_6);
if (get_env_result == JNI_EDETACHED) {
if (vm->AttachCurrentThread(env, NULL) == JNI_OK) {
did_attach_thread = true;
} else {
// Failed to attach thread. Throw an exception if you want to.
}
} else if (get_env_result == JNI_EVERSION) {
// Unsupported JNI version. Throw an exception if you want to.
}
return did_attach_thread;
}
您的使用方式是:
JNIEnv *env;
bool did_attach = GetJniEnv(vm, &env);
// Use env...
// ...
if (did_attach) {
vm->DetachCurrentThread();
}
你可以把它包装在一个 class 中,它在构造时附加在破坏时分离,RAII 风格:
class ScopedEnv {
public:
ScopedEnv() : attached_to_vm_(false) {
attached_to_vm_ = GetJniEnv(g_vm, &env_); // g_vm is a global
}
ScopedEnv(const ScopedEnv&) = delete;
ScopedEnv& operator=(const ScopedEnv&) = delete;
virtual ~ScopedEnv() {
if (attached_to_vm_) {
g_vm->DetachCurrentThread();
attached_to_vm_ = false;
}
}
JNIEnv *GetEnv() const { return env_; }
private:
bool attached_to_env_;
JNIEnv *env_;
};
// Usage:
{
ScopedEnv scoped_env;
scoped_env.GetEnv()->SomeJniFunction();
}
// scoped_env falls out of scope, the thread is automatically detached if necessary
编辑: 有时您可能有一个较长的 运行 本机线程,在多个场合需要 JNIEnv*
。在这种情况下,您可能希望避免不断地附加和分离线程 to/from JVM,但您仍然需要确保在线程销毁时分离线程。
您可以通过仅附加线程一次然后保持附加状态,并使用 pthread_key_create
和 pthread_setspecific
设置线程销毁回调来实现此目的,这将负责调用 DetachCurrentThread
.
/**
* Get a JNIEnv* valid for this thread, regardless of whether
* we're on a native thread or a Java thread.
* If the calling thread is not currently attached to the JVM
* it will be attached, and then automatically detached when the
* thread is destroyed.
*/
JNIEnv *GetJniEnv() {
JNIEnv *env = nullptr;
// We still call GetEnv first to detect if the thread already
// is attached. This is done to avoid setting up a DetachCurrentThread
// call on a Java thread.
// g_vm is a global.
auto get_env_result = g_vm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (get_env_result == JNI_EDETACHED) {
if (g_vm->AttachCurrentThread(&env, NULL) == JNI_OK) {
DeferThreadDetach(env);
} else {
// Failed to attach thread. Throw an exception if you want to.
}
} else if (get_env_result == JNI_EVERSION) {
// Unsupported JNI version. Throw an exception if you want to.
}
return env;
}
void DeferThreadDetach(JNIEnv *env) {
static pthread_key_t thread_key;
// Set up a Thread Specific Data key, and a callback that
// will be executed when a thread is destroyed.
// This is only done once, across all threads, and the value
// associated with the key for any given thread will initially
// be NULL.
static auto run_once = [] {
const auto err = pthread_key_create(&thread_key, [] (void *ts_env) {
if (ts_env) {
g_vm->DetachCurrentThread();
}
});
if (err) {
// Failed to create TSD key. Throw an exception if you want to.
}
return 0;
}();
// For the callback to actually be executed when a thread exits
// we need to associate a non-NULL value with the key on that thread.
// We can use the JNIEnv* as that value.
const auto ts_env = pthread_getspecific(thread_key);
if (!ts_env) {
if (pthread_setspecific(thread_key, env)) {
// Failed to set thread-specific value for key. Throw an exception if you want to.
}
}
}
如果您可以使用 __cxa_thread_atexit
,您也许可以使用在其析构函数中调用 DetachCurrentThread
的某些 thread_local
对象来完成同样的事情。
@Michael,很好地概述了如何通过缓存 JVM 来最好地检索 JNI。
对于那些不想使用 pthread(或者不能'因为你在 Windows 系统上),并且你正在使用 c++ 11 或更高版本的人,那么 thread_local 存储是要走的路。
Bellow 是关于如何实现正确附加到线程并在线程退出时自动清理的包装方法的粗略示例
JNIEnv* JNIThreadHelper::GetJniEnv() {
// This method might have been called from a different thread than the one that created
// this handler. Check to make sure that the JNI is attached and if not attach it to the
// new thread.
// double check it's all ok
int nEnvStat = m_pJvm->GetEnv(reinterpret_cast<void**>(&m_pJniEnv), JNI_VERSION_1_6);
if (nEnvStat == JNI_EDETACHED) {
std::cout << "GetEnv: not attached. Attempting to attach" << std::endl;
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // choose your JNI version
args.name = NULL; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
if (m_pJvm->AttachCurrentThread(&m_pJniEnv, &args) != 0) {
std::cout << "Failed to attach" << std::endl;
return nullptr;
}
thread_local struct DetachJniOnExit {
~DetachJniOnExit() {
m_pJvm->DetachCurrentThread();
}
};
m_bIsAttachedOnAThread = true;
}
else if (nEnvStat == JNI_OK) {
//
}
else if (nEnvStat == JNI_EVERSION) {
std::cout << "GetEnv: version not supported" << std::endl;
return nullptr;
}
return m_pJniEnv;
}
我有一个使用 JNI 的 Android 项目。在实现监听器 class 的 CPP 文件中,有一个回调 x() 。当调用 x() 函数时,我想在 java class 中调用另一个函数。但是,为了调用 java 函数,我需要访问 JNIEnv*。
我知道在回调的同一个cpp文件中,有一个函数:
static jboolean init (JNIEnv* env, jobject obj) {...}
调用init(..)
时是否需要在cpp文件中保存JNIEnv*作为成员变量?并在回调发生时使用它?
抱歉,我是 JNI 的初学者。
缓存 JNIEnv*
不是一个特别好的主意,因为您不能在多个线程中使用相同的 JNIEnv*
,甚至可能无法将它用于多个本机调用同一线程(参见 http://android-developers.blogspot.se/2011/11/jni-local-reference-changes-in-ics.html)
编写一个获取 JNIEnv*
并在必要时将当前线程附加到 VM 的函数并不难:
bool GetJniEnv(JavaVM *vm, JNIEnv **env) {
bool did_attach_thread = false;
*env = nullptr;
// Check if the current thread is attached to the VM
auto get_env_result = vm->GetEnv((void**)env, JNI_VERSION_1_6);
if (get_env_result == JNI_EDETACHED) {
if (vm->AttachCurrentThread(env, NULL) == JNI_OK) {
did_attach_thread = true;
} else {
// Failed to attach thread. Throw an exception if you want to.
}
} else if (get_env_result == JNI_EVERSION) {
// Unsupported JNI version. Throw an exception if you want to.
}
return did_attach_thread;
}
您的使用方式是:
JNIEnv *env;
bool did_attach = GetJniEnv(vm, &env);
// Use env...
// ...
if (did_attach) {
vm->DetachCurrentThread();
}
你可以把它包装在一个 class 中,它在构造时附加在破坏时分离,RAII 风格:
class ScopedEnv {
public:
ScopedEnv() : attached_to_vm_(false) {
attached_to_vm_ = GetJniEnv(g_vm, &env_); // g_vm is a global
}
ScopedEnv(const ScopedEnv&) = delete;
ScopedEnv& operator=(const ScopedEnv&) = delete;
virtual ~ScopedEnv() {
if (attached_to_vm_) {
g_vm->DetachCurrentThread();
attached_to_vm_ = false;
}
}
JNIEnv *GetEnv() const { return env_; }
private:
bool attached_to_env_;
JNIEnv *env_;
};
// Usage:
{
ScopedEnv scoped_env;
scoped_env.GetEnv()->SomeJniFunction();
}
// scoped_env falls out of scope, the thread is automatically detached if necessary
编辑: 有时您可能有一个较长的 运行 本机线程,在多个场合需要 JNIEnv*
。在这种情况下,您可能希望避免不断地附加和分离线程 to/from JVM,但您仍然需要确保在线程销毁时分离线程。
您可以通过仅附加线程一次然后保持附加状态,并使用 pthread_key_create
和 pthread_setspecific
设置线程销毁回调来实现此目的,这将负责调用 DetachCurrentThread
.
/**
* Get a JNIEnv* valid for this thread, regardless of whether
* we're on a native thread or a Java thread.
* If the calling thread is not currently attached to the JVM
* it will be attached, and then automatically detached when the
* thread is destroyed.
*/
JNIEnv *GetJniEnv() {
JNIEnv *env = nullptr;
// We still call GetEnv first to detect if the thread already
// is attached. This is done to avoid setting up a DetachCurrentThread
// call on a Java thread.
// g_vm is a global.
auto get_env_result = g_vm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (get_env_result == JNI_EDETACHED) {
if (g_vm->AttachCurrentThread(&env, NULL) == JNI_OK) {
DeferThreadDetach(env);
} else {
// Failed to attach thread. Throw an exception if you want to.
}
} else if (get_env_result == JNI_EVERSION) {
// Unsupported JNI version. Throw an exception if you want to.
}
return env;
}
void DeferThreadDetach(JNIEnv *env) {
static pthread_key_t thread_key;
// Set up a Thread Specific Data key, and a callback that
// will be executed when a thread is destroyed.
// This is only done once, across all threads, and the value
// associated with the key for any given thread will initially
// be NULL.
static auto run_once = [] {
const auto err = pthread_key_create(&thread_key, [] (void *ts_env) {
if (ts_env) {
g_vm->DetachCurrentThread();
}
});
if (err) {
// Failed to create TSD key. Throw an exception if you want to.
}
return 0;
}();
// For the callback to actually be executed when a thread exits
// we need to associate a non-NULL value with the key on that thread.
// We can use the JNIEnv* as that value.
const auto ts_env = pthread_getspecific(thread_key);
if (!ts_env) {
if (pthread_setspecific(thread_key, env)) {
// Failed to set thread-specific value for key. Throw an exception if you want to.
}
}
}
如果您可以使用 __cxa_thread_atexit
,您也许可以使用在其析构函数中调用 DetachCurrentThread
的某些 thread_local
对象来完成同样的事情。
@Michael,很好地概述了如何通过缓存 JVM 来最好地检索 JNI。 对于那些不想使用 pthread(或者不能'因为你在 Windows 系统上),并且你正在使用 c++ 11 或更高版本的人,那么 thread_local 存储是要走的路。
Bellow 是关于如何实现正确附加到线程并在线程退出时自动清理的包装方法的粗略示例
JNIEnv* JNIThreadHelper::GetJniEnv() {
// This method might have been called from a different thread than the one that created
// this handler. Check to make sure that the JNI is attached and if not attach it to the
// new thread.
// double check it's all ok
int nEnvStat = m_pJvm->GetEnv(reinterpret_cast<void**>(&m_pJniEnv), JNI_VERSION_1_6);
if (nEnvStat == JNI_EDETACHED) {
std::cout << "GetEnv: not attached. Attempting to attach" << std::endl;
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // choose your JNI version
args.name = NULL; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
if (m_pJvm->AttachCurrentThread(&m_pJniEnv, &args) != 0) {
std::cout << "Failed to attach" << std::endl;
return nullptr;
}
thread_local struct DetachJniOnExit {
~DetachJniOnExit() {
m_pJvm->DetachCurrentThread();
}
};
m_bIsAttachedOnAThread = true;
}
else if (nEnvStat == JNI_OK) {
//
}
else if (nEnvStat == JNI_EVERSION) {
std::cout << "GetEnv: version not supported" << std::endl;
return nullptr;
}
return m_pJniEnv;
}