Uninitializing and Deleting Instances Using UNINIT

Normally, object classes can create instances but have no direct control over their deletion. Once an object is no longer referenced in the program, it turns to garbage and Rexx automatically reclaims the storage it occupies in the computer's memory in a process called garbage collection.

If the instance has allocated other system resources, Rexx cannot automatically release these resources because it is unaware that the instance has allocated them. An UNINIT method gives an object the opportunity to perform resource cleanup before the object is reclaimed by the garbage collector. This is done by the garbage collector for objects having an UNINIT method implemented right before the object gets destroyed by sending it the UNINIT message. Because this method runs at destruction time only it is called the Rexx desctructor method.

In the following example the NEW message gets an argument supplied that is meant to be used for setting the value of the object variable (attribute) text in the scratchpad class. As mentioned above the NEW method, after creating the instance, but before returning it gets the INIT message sent with the argument it received and will save that value in its text object variable (attribute) and displays that value using. the SAY instruction.

Once the program is finished and the objects get destroyed by the garbage collector, each scratchpad object will get the UNINIT message sent to it, which in turn runs UNINIT method. The method directly accesses teh text object variable (attribute) and displays its value with the SAY instruction:


UNINIT Method
/* uninit&per;cmd - example of UNINIT processing */
a=.scratchpad~new("Of all the things I've lost")
a=.scratchpad~new("I miss my mind the most")
say "Exiting program."
exit
::class scratchpad
::method init
expose text
use arg text
say "Remembering" text
::method uninit
expose text
say "Forgetting" text
return

Whether uninitialization processing is needed depends on the circumstances, If the object only contains references to normal Rexx objects, an UNINIT method is generally not needed. If the object contains references to external system resources such as open network connections or database connections, an UNINIT method might be required to release those resources. If an object requires uninitialization, define an UNINIT method to perform the cleanup processing you require.

If an object has an UNINIT method, Rexx runs it before reclaiming the object's storage. If an instance overrides an UNINIT method of a superclass, each UNINIT method is responsible for sending the UNINIT message up the hierarchy, using the SUPERCLASS overrides (by using the statement: "self~uninit:super"), so that each inherited UNINIT method has the opportunity to run.