The goal is to be able to invoke execution of a separate thread from within the main class.
Some context: I have a program that must ru
To spawn a process that survives after the JVM terminates you'll need to use Runtime.exec()
. Since you want it to run after your main process ends, there are really two ways you can do it:
1) If you only want to process to run during a clean shutdown then you can do this:
public static void main(String[] args) {
doThisProgramsStuff();
spawnSecondProcess();
}
2) Or, if you want the process to run even with an unclean shutdown (or if it's a GUI application) then you can add a shutdown hook:
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
spawnSecondProcess();
}
});
doThisProgramsStuff();
}
There is, however, a problem with all this. Once the JVM terminates the child process will have standard input/output attached to nothing, so it might fill it's output buffers and block. You'll need to do something to make sure this doesn't happen by either making sure the process does not produce output to those streams or by doing the Windows equivalent of redirecting to /dev/null.