[ACCEPTED]-JNI objects creation and memory management-java-native-interface

Accepted answer
Score: 16

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

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

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

In most 7 cases, the programmer should rely on the 6 VM to free all local references after the 5 native method returns. However, there are 4 times when the programmer should explicitly 3 free a local reference. Consider, for example, the 2 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 1 provided See "Freeing References" in the JNI Programmer's Guide.

More Related questions