Hi,
Discussions on stopping threads have been up on this forum before but I feel my particular case hasn't been aswered yet.
I have a program that makes a methodcall that sometimes doesn't return for a long period of time. There are users waiting for the program to produce a response and they aren't prepared to wait for to long.
I want to be able to return a response within a specified amount of time regardless of if the method returned or not. If the method prouduces a result, fine, then I'll show that to the users. But after a specified amount of time, if the method hasn't returned a response, I want to tell the users that a result isn't possible to produce at the moment.
To solve this problem the mainMethod starts a thread that executes the methodcall. The main program don't wait for more than the specified amount of time. If no result has been produced by the thread at that time a null result is returned. If the thread produces a result within the timeframe it is returned to the users.
This is the way I do this:
My problem is that the call to interrupt() doesn't stop the thread. When mainMethod returns, the thread will still be alive in the VM. Since there might be hundreds of calls to mainMethod every hour, several hundreds of threads will be out there blocking on that method and eating up the resources of the server. And there will be more and more as time passes.Code:public class Worker implements Runnable {
private String result;
public run() {
result = blockingMethodCall();
}
public String getResult() {
return result;
}
}
public class MainProgram {
public void mainMethod() {
...
Worker worker = new Worker();
Thread thread = new Thread(worker);
thread.start();
// Returns when finished executing, or after maximum TIME_OUT time
thread.join(TIME_OUT);
if (thread.isAlive()) {
// If the thread is still alive, it's still blocking on the methodcall, try stopping it
thread.interrupt();
return null;
} else {
// The thread is finished, get the result
return worker.getResult();
}
}
}
So, how will I solve this problem? If I at least could kill of the thread...