The class is instantiated when
the USE statement is first encountered in a session, and then it is
released when the session ends or the DROP statement is executed.
As a result, the state can be kept in a normal class and static variables
can be maintained. Here is an example:
public
class Hello
{
static int count = 0;
int instance;
int iteration = 0;
public Hello()
{
instance = count++;
System.out.println("Hello constructor " + instance);
}
public double addOne(double d)
{
System.out.println("addOne, world! " + instance + " " +
iteration++);
return d+1.0;
}
public void finalize()
{
System.out.println("Hello finalize");
}
}
Note: System.out
is used in the above example for illustration and cannot be used
in a real function except for debugging.
Here is an example
of the debugging output that is generated:
Hello constructor 0
addOne, world! 0 0
addOne, world! 0 2
Hello constructor 1
addOne, world! 0 3
addOne, world! 1 0
addOne, world! 1 1
Each time a new session (a user or client connection) uses this
class, the Java constructor is called and a new
Hello
object is created. The count is incremented so that
instance
has a unique value. Example items that
you might want to save in a real application include file handles,
shopping cart lists, and database connection handles.
Although
cleanup is automatic, you can have an optional
finalize method for special circumstances. Normal
Java garbage collection of the class occurs some time after the class
is no longer needed. The finalize method should then be called. However,
in accordance with Java standards, it is possible that the finalize
method will never be called (for example, if the server is shut down
early, or the class never needs to be removed by the garbage collector).