I'm starting a Process from a Java program. I hold onto it and at later points in the program I may send it some signals (not as in UNIX signals -- a different mechanism) to tell it to clean itself up and shut down, which is the proper way of terminating this process. I may later restart and hold onto the process and stop it again an arbitrary number of times.
I'd like my program, when it exists, to signal the Process to terminate and make sure it exists. Otherwise, since Java starts the process up asynchronously, it persists and continues to run after my program terminates.
I thought I would do this in the destructor for the object that contains the Process variable, but it seems that Java does not have a destructor. It has a finalize() method for freeing memory allocated through JNI, but this is not such a case, and apparently you can't guarantee that finalize() will be called: it is only called when the object is garbage collected, and the program might run through to termination without ever calling garbage collection, in which case everything is freed at once and no garbage collection and no finalize() occurs.
What's the best way to make sure that when my program exits this cleanup code gets called first?
I see that Java 1.6 has introduced a Runtime.addShutdownHook() method, but I am currently stuck on Java 1.5.