Using objects that no longer exist

If you have static Object variables in your native method (STATIC keyword on the definition), or your native method uses static global Object variables (variables declared in the main source section), then the Object variables will retain their values between calls to the native method. However, by default, Java™ will free any objects created during a call to a native method. (See Additional RPG Coding for Using Java to see how to prevent Java from freeing objects.)

An RPG "Object" is really a numeric object reference. When a Java object is freed, the numeric object reference can be reused. If the RPG native method refers to a static Object variable that has not been explicitly protected from being freed, one of two things can happen:
  1. The object reference may be invalid, if the numeric object reference has not been reused.
  2. The object reference may have been reused, but since it refers to a different object, any attempt to use it in the RPG native method will probably be incorrect.
To prevent problems with attempting to reuse objects illegally, the RPG programmer may do one or more of the following:
  • Avoid declaring any Object variables in static storage. Instead, declare all Object variables in local storage of subprocedures, without using the STATIC keyword.
  • Before returning from a native method, explicitly set all static object references to *NULL.
  • Upon entering a native method, explicitly set all static object references to some initial values.