简体   繁体   English

JNI 本地参考空闲时间

[英]JNI Local Reference Free Time

According to The Official Documentation Says:根据官方文档说:

Local references are valid for the duration of a native method call, and are automatically freed after the native method returns本地引用在本地方法调用期间有效,并在本地方法返回后自动释放

Imaging a case, We have a native framework a.so成像一个案例,我们有一个原生框架a.so

And we load it.我们加载它。

static JavaVM * g_cachedJVM;

CJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM * jvm, void * /*reserved*/) {

    g_cachedJVM = jvm;
    return JNI_VERSION_1_6;
}

And we call a native method implement by a.so , we start a c++ timer in this method.我们通过a.so调用原生方法实现,我们在这个方法中启动了一个 c++ 定时器。

CJNIEXPORT jobject JNICALL Java_A_Custom_Method(JNIEnv* jniEnv, jobject /*this*/) {
   startTimerInCurrentTheadWithoutBlockCurrentThread(Seconds(1),[](){
       //invoke method every 1 second
       cppMethod();
   });
}

void cppMethod() {
    //Create some jni local reference use g_cachedJVM
    // what is the life cycle of the local reference?
}

Question: what is the life cycle of the local reference in the cpp method问题:cpp方法中本地引用的生命周期是什么

Since your cppMethod is a native method you need handle local references by yourself.由于您的cppMethod是本机方法,因此您需要自己处理本地引用。
Technically your local references will be bound to JNIEnv and older versions of the jvm did release all references when their Env was removed.从技术上讲,您的本地引用将绑定到JNIEnv ,并且旧版本的 jvm 在删除其Env时确实释放了所有引用。
But I am not aware that this behaviour is somewhere specified.但我不知道这种行为是在某处指定的。

So to anwer your question:所以回答你的问题:

  1. All local references you create will be bound to the JNIEnv that you created您创建的所有本地引用都将绑定到您创建的JNIEnv
  2. If you do not release your local references they will remain valid for ever.如果您不发布您的本地参考资料,它们将永远有效。

Therefore is is usually best to always handle your local references, although it is not needed in JNI calls.因此,通常最好始终处理本地引用,尽管在 JNI 调用中不需要它。
You can make this handling simpler with a RAII wrapper around PushLocalFrame/PopLocalFrame您可以使用围绕PushLocalFrame/PopLocalFrameRAII包装器简化此处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM