How do I cleanup an opened Process in Java?

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.


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...


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.

链接地址: http://www.djcxy.com/p/19912.html

上一篇: 重写后退按钮以充当主页按钮

下一篇: 如何清理Java中打开的Process?