Deleting, saving, and freeing local references

You can manually delete local references at any point within a method. Save local references only in object references that you define in the LOCAL-STORAGE SECTION of a method.

About this task

Use a SET statement to convert a local reference to a global reference if you want to save a reference in any of these data items:

  • An object instance variable
  • A factory variable
  • A data item in the WORKING-STORAGE SECTION of a method

Otherwise, an error occurs. These storage areas persist when a method returns; therefore a local reference is no longer valid.

In most cases you can rely on the automatic freeing of local references that occurs when a method returns. However, in some cases you should explicitly free a local reference within a method by using the JNI service DeleteLocalRef. Here are two situations where explicit freeing is appropriate:

  • In a method you access a large object, thereby creating a local reference to the object. After extensive computations, the method returns. Free the large object if you do not need it for the additional computations, because the local reference prevents the object from being released during garbage collection.
  • You create a large number of local references in a method, but do not use all of them at the same time. Because the Java™ virtual machine requires space to keep track of each local reference, you should free those that you no longer need. Freeing the local references helps prevent the system from running out of memory.

    For example, in a COBOL method you loop through a large array of objects, retrieve the elements as local references, and operate on one element at each iteration. You can free the local reference to the array element after each iteration.

Use the following callable services to manage local references and global references.

Table 1. JNI services for local and global references
Service Input arguments Return value Purpose
NewGlobalRef
  • The JNI environment pointer
  • A local or global object reference
The global reference, or NULL if the system is out of memory To create a new global reference to the object that the input object reference refers to
DeleteGlobalRef
  • The JNI environment pointer
  • A global object reference
None To delete a global reference to the object that the input object reference refers to
DeleteLocalRef
  • The JNI environment pointer
  • A local object reference
None To delete a local reference to the object that the input object reference refers to

Related tasks  
Accessing JNI services