Reputation: 12267
My main process calls an external library method. This method sometimes hangs. I can not fix the external library because another company is responsible for it.
I want to use a Thread for the library calls with a defined execution timer. When the method call takes to long, the Thread with the Runnable in which the method call is placed should stop and the main process should go forward.
Does anybody have some code this logic is for, a design pattern i can use or a internet page i can read some informations?
Thanks
Upvotes: 4
Views: 2459
Reputation: 8360
Take a look at the java.lang.concurrent
package in Java 5 and later, in particular the CompletionService
interface and the classes that implement it.
This interface includes calls that allow you to submit a task and either wait for it to complete, or else continue after a timeout.
Upvotes: 2
Reputation: 103847
You won't be able to magically make the running thread stop after 30 seconds; what you would need to do is make that thread check some state after the time is up, notice it's taken too long and return
from its run method.
There are roughly two approaches to doing this:
In both cases, you'd need to have one of the threads (probably the main thread as it has nothing else to do) set the "stop" flag to true
once the time is up (and this variable should be declared volatile so updates are seen by all threads). Likewise, when the library call thread sees this flag as true, it should stop what it's doing, generally by returning from the run() method.
You shouldn't really kill the library thread from the main thread; see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated for the reasons, and an alternative that looks very much like what I've described above. :-)
Upvotes: 1
Reputation:
This will wait up to 30 seconds for the thread to finish.
Thread t = new Thread() {
public void run() {
badExternalMethod();
synchronized (this) {
notifyAll();
}
}
};
synchronized (t) {
t.start();
try {
t.wait(30000); // 30 secs
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// t has completed or timed out
Upvotes: 2