Static and non-final variables in a Java routine
Using Java variables
that are defined as static but not final can
cause problems for Java routines.
- Use of variables that are static and non-final reduces portability.
Because the ANSI/ISO standard does not include support for static and non-final variables, different database products might process those variables differently.
- A sequence of routine invocations is not necessarily processed
by the same JVM, and static variable values are not shared among different
JVMs.
For example, suppose that two stored procedures, INITIALIZE and PROCESS, use the same static variable, sv1. INITIALIZE sets the value of sv1, and PROCESS depends on the value of sv1. If INITIALIZE runs in one JVM, and then PROCESS runs in another JVM, sv1 in PROCESS does not contain the value that INITIALIZE set.
Specifying NUMTCB=1 in the WLM-established stored process space startup procedure is not sufficient to guarantee that a sequence of routine invocations go to the same JVM. Under load, multiple stored procedure address spaces are initiated, and each address space has its own JVM. Multiple invocations might be directed to multiple address spaces.
- In Java, the static variables for a class are initialized or reset whenever the class is loaded. However, for Java routines, it is difficult to know when initialization or reset of static variables occurs.
In certain cases, you need to declare variables as static and non-final. In those cases, you can use the following technique to make your routines work correctly with static variables.
To determine whether the values of static data in a routine have persisted across routine invocations, define a static boolean variable in the class that contains the routine. Initially set the variable to false, and then set it to true when you set the value of static data. Check the value of the boolean variable at the beginning of the routine. If the value is true, the static data has persisted. Otherwise, the data values need to be set again. With this technique, static data values are not set for most routine invocations, but are set more than once during the lifetime of the JVM. Also, with this technique, it is not a problem for a routine to execute on different JVMs for different invocations.