C++ 调用的 JNI localrefs 的生命周期是多少 Java?

What is the lifetime of JNI localrefs for C++ calling Java?

当Java通过JNI调用C函数时,我们知道一旦C函数returns调用[=30],任何对类或对象的局部引用都可能失效=].

然而,当我们只有 C 调用 Javam 时,没有 "return to java"。所以我不清楚这些引用何时会失效。

例如,这是 不好的,因为 aClass,一旦调用完成,anObject 可能会失效。

jclass aClass;
jobject anObject;

JNIEXPORT void JNICALL Java_example_method1(JNIEnv *env) {
    aClass = env->FindClass("AClass");
}

JNIEXPORT void JNICALL Java_example_method2(JNIEnv * env) {
    jmethodID constructor = env->GetMethodID( aClass, "<init>", "()V");
    anObject = env->NewObject(klass, constructor );
}

但是在下面的例子中,什么会导致aClassanObject失效呢?它只是对 DeleteLocalRef 的显式调用吗?

jclass aClass;
jobject anObject;

int main() {
        JavaVMInitArgs vm_args;
        JavaVMOption options[1];
        vm_args.version = JNI_VERSION_1_6;
        vm_args.nOptions = 1;
        options[0].optionString = "-Djava.class.path=.";
        vm_args.options = options;
        vm_args.ignoreUnrecognized = JNI_FALSE;
        JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);

        aClass = env->FindClass("AClass");
        jmethodID constructor = env->GetMethodID( aClass, "<init>", "()V");
        anObject = env->NewObject(klass, constructor );
}

没错。当 Java 调用 JNI 时,它会分配一个 table 本地引用到的地方,当 JNI returns 时全部释放。当你打电话时 Java 没有这样的机制。

Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.

Local references are only valid in the thread in which they are created.

Source