10.43.8.4 Global vs. Local References

It is important to understand the rules determining the life-span of Java object references. These are similar in spirit to the SP_term_refs of the C-Prolog interface, but since they are used to handle Java objects instead of Prolog terms they work a little differently.

Java object references (currently represented in Prolog as '$java_object'/1 terms) exist in two flavors: local and global. Their validity are governed by the following rules.

  1. A local reference is valid until Prolog returns to Java or the reference is deleted with jasper_delete_local_ref/2. It is only valid in the (native) thread in which is was created. As a rule of thumb a local reference can be used safely as long as it is not saved away using assert/3 or similar.

    Since local references are never reclaimed until Prolog returns to Java (which may never happen) you should typically call jasper_delete_local_ref/2 when your code is done with an object.

  2. A global reference is valid until explicitly freed. It can be used from any native thread.
  3. All objects returned by Java methods are converted to local references.
  4. Java exceptions not caught by Java are thrown as Prolog exceptions consisting of a global reference to the exception object, see Handling Java Exceptions.

Local references can be converted into global references (jasper_create_global_ref/3). When the global reference is no longer needed, it should be delete using jasper_delete_global_ref/2.

For a more in-depth discussion of global and local references, consult the JNI Documentation.

Using a local (or global) reference that has been deleted (either explicitly or by returning to Java) is illegal and will generally lead to crashes. This is a limitation of the Java Native Interface used to implement the low level interface to Java.


Send feedback on this subject.