JNI objects creation and memory management

2019-02-08 13:14发布

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;
}

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?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-08 13:36

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.

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: "Global and local references" in the JNI specification.

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:

  • A native method accesses a large Java object, thereby creating a local reference to the Java object. The native method then performs additional computation before returning to the caller. The local reference to the large Java object will prevent the object from being garbage collected, even if the object is no longer used in the remainder of the computation.
  • A native method creates a large number of local references, although not all of them are used at the same time. Since the VM needs a certain amount of space to keep track of a local reference, creating too many local references may cause the system to run out of memory. For example, a native method loops through a large array of objects, retrieves the elements as local references, and operates on one element at each iteration. After each iteration, the programmer no longer needs the local reference to the array element.

Additional detail was provided See "Freeing References" in the JNI Programmer's Guide.

查看更多
登录 后发表回答