views:

167

answers:

2

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.

+3  A: 

Try/finally is the closest that you will get toe a C++ destructor.

Process process;

process = ....;

try
{
    // do work
}
finally
{
    // send info to process to shut it down
}

Also, addShutdownHook was added in 1.3...

TofuBeer
try/finally doesn't work here. My program is nowhere near that linear, and the cleanup code is never going to happen in the method that started the process, ever. It has to happen when the user terminates the program, and I have no idea when that is. However --
skiphoppy
Pointing out that addShutdownHook() came in in 1.3 gives me exactly what I want. (And teaches me not to assume that everything I read in StackOverflow answers is correct ... I picked up the 1.6 figure from another question here.) Thanks!!
skiphoppy
You can make the try/finally work probably - it just might take a bit... but glad you figured it out.
TofuBeer
+1  A: 

Why not call it before you call System.exit? Your code should probably be structured so you're only calling System.exit from one place (or returning from main), either way that would be a good way to go.

Bill K
I would love to structure my code in that way, but I don't think I can. The user might click the X button, the user might click the "finish" button, the user might kill the program using operating-system facilities.
skiphoppy
If all those places use System.exit(), couldn't they just as easily call a static .exit routine you define that first closes your resources then exits?
Bill K