JNI对象创建和内存管理 [英] JNI objects creation and memory management

查看:178
本文介绍了JNI对象创建和内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JNI方法创建本机的Java对象集合,然后将它们返回到Java:

I have the following JNI method that creates a collection of Java objects natively, and then return them to Java:

JNIEXPORT jobject JNICALL Java_com_test_myClass_myMethod(JNIEnv * env, jclass klass) {
    jclass arrayClass = env->FindClass("java/util/ArrayList");
    jmethodID initMethod = env->GetMethodID(arrayClass, "<init>", "()V");
    jmethodID addMethod = env->GetMethodID(arrayClass, "add", "(Ljava/lang/Object;)Z");
    jobject myArray = env->NewObject(arrayClass, initMethod);

    env->CallBooleanMethod(myArray, addMethod, env->NewStringUTF("Hello"));
    env->CallBooleanMethod(myArray, addMethod, env->NewStringUTF("World"));

    return myArray;
}

我需要释放在本机代码中创建的对象,由GC自动完成?

Do I need to free the objects created in the native code, or is it done automatically by the GC? If I do, how do I do that, as I need to return it to Java?

推荐答案

如果我这样做,不需要释放在本地代码中创建的Java对象。事实上,你不能。

You do not need to free the Java objects created in the native code. In fact, you cannot. The garbage collector may free the object when no further references remain.

有时候,在本地代码中对于Java对象释放引用是很有用的。这可以减少内部代码存储,但不再需要,引用大对象或大量引用时的内存需求。

Occasionally it is useful in native code to free references to Java objects. This can reduce memory requirements when the native code holds, but no longer needs, references to large objects or a large number of references.

From:全局和局部引用 JNI规范中。

From: "Global and local references" in the JNI specification.


在大多数情况下,程序员应该依赖VM在native方法返回后释放所有本地引用。然而,有时候程序员应该明确地释放一个本地引用。例如,考虑以下情况:

In most cases, the programmer should rely on the VM to free all local references after the native method returns. However, there are times when the programmer should explicitly free a local reference. Consider, for example, the following situations:


  • 本地方法访问大型Java对象,从而创建对Java对象的本地引用。然后,本地方法在返回到调用者之前执行附加计算。对大型Java对象的本地引用将阻止对象被垃圾回收,即使该对象在计算的其余部分中不再使用。

  • 本地方法创建大数字的地方参考文献,虽然不是所有的参考文献都同时使用。由于VM需要一定量的空间来跟踪本地引用,因此创建太多的本地引用可能会导致系统内存不足。例如,本地方法循环遍历大量对象,检索元素作为本地引用,并在每次迭代时对一个元素进行操作。每次迭代后,程序员不再需要数组元素的本地引用。

已提供
请参阅JNI程序员指南中的免费参考

这篇关于JNI对象创建和内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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