缓存JNI对象和线程安全性(在Android中) [英] Caching JNI objects and thread-safety (in Android)

查看:181
本文介绍了缓存JNI对象和线程安全性(在Android中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用本机线程(pthread)编写C ++应用程序,并且需要调用一些Java方法等.我不确定哪些JNI对象可以安全地缓存,即存储在我的C ++对象中以便以后使用,可能/可能是通过不同的线程.我确实知道,如果我的类的方法可以由不同的线程调用,则我不必缓存JNIEnv,而应该缓存JavaVM并通过附加当前线程来获取JNIEnv.但这是否还意味着我无法缓存从JNIEnv获得的任何内容?我需要使用通过以下JNIEnv方法获得的对象:

I'm writing a C++ app with native threads (pthreads) and I need to call some Java methods etc. I'm not sure which JNI objects can be safely cached ie stored in my C++ object for use later, possibly/probably by a different thread. I do know that if my class' methods can be called by different threads I mustn't cache the JNIEnv, but instead cache the JavaVM and get a JNIEnv by attaching the current thread. But does that also mean I can't cache anything obtained from a JNIEnv? I need to use the objects obtained by the following JNIEnv methods:

FindClass,GetMethodID,NewObject,NewGlobalRef

FindClass, GetMethodID, NewObject, NewGlobalRef

这些线程在各个线程之间仍然有效吗,还是我每次都必须获取新的线程?如果是后者,是否有办法在一个本机线程中创建对象并能够在其他线程中访问同一对象?

Do those stay valid across threads, or do I have to get new ones every time? If the latter, is there a way to create an object in one native thread and be able to access the same object in a different thread?

推荐答案

对象不是特定于线程的.它们最初是本地"引用,如果要保留副本,则必须通过创建(并最终删除)全局"引用来告知VM您正在这样做.

Objects are not thread-specific. They are initially "local" references, and if you want to keep a copy you have to tell the VM that you're doing so by creating (and, eventually, deleting) a "global" reference.

请参见 http://developer.android.com/training/articles/perf -jni.html ,尤其是本地和全局引用"部分.

See http://developer.android.com/training/articles/perf-jni.html, especially the "Local and Global References" section.

这篇关于缓存JNI对象和线程安全性(在Android中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆