I have developed a JSP web application which, on every request, spawns a new Java Thread. In every newly spawned thread I create a Process using Runtime.exec() and store the process object in an instance variable in thread. I have a requirement in which I have to kill the created subprocess and also stop the thread. So, I overrode the interrupt method in the thread and in the overridden method I’m calling destroy() on already stored Process object in the instance variable. Following is the code:
public class MyThread extends Thread {
private Process subprocess;
@Override
public void run() {
subprocess = Runtime.getRuntime().exec("myprocess.exe");
subprocess.waitFor();
/*
Some more statements
*/
}
@Override
public void interrupt() {
if(subprocess!=null) {
System.out.println("Destroying Process");
subprocess.destroy();
}
super.interrupt();
}
}
Is it illeagal to override interrupt method?
Its important that I kill the created process before I interrupt the thread that creates it. I see that the thread does get interrupted because the statements after waitFor() do not get executed. But, however, destroy() doesnt work (but gets called) and the created “myprocess.exe” completes execution even if I call interrupt() method before its completion. Can someone please help me out with this? What am I missing?
Thanks in advance
It’s not illegal to override
interrupt, but I wouldn’t recommend it. Perhaps a cleaner way to do this would be:Don’t forget that you should also pull data from the subprocess output/error streams, otherwise you might wind up with full buffers and a blocked subprocess. It’s OK to read from those streams and discard the data. I suspect the
commons-iopackage has tools to make this a one-liner, otherwise it’s a fairly simple method to write yourself.