-
Implement a timeout
Hello
I would like to implement a timeout on my java application.
Imagine that I am calling a method ("test()" for example) that I cannot modify. I want to stop the process if no answer is returned by this method after 60 seconds.
How can I do that?
Thanks
-
You want full code or just discussion.
Timer and TimerTask
-
Tic Toc ...
Taking Nicholas's comment a little further:
Timer (Java Platform SE 6)
TimerTask (Java Platform SE 6)
Luck,
CJSL
-
Thanks, i dont know theses classes but I will check...
regards
-
( cannot see your reply )
Okay, but what you will find is rather deep. Timer and Timer Task try to run - you can make it run for your timeout interval, but better is to do a check of a variable doing Timer / TimerTask.cancel if variable changes to false. In other words, we are coding a softened version of a spin-lock. It sorta depends on your skill level and willingness to code. There are also Threading issues, the Thread class has some sort of done() method, and there are ways of doing a 'stop task' that do not involve hanging the machine.
test() cannot block unless you want to get into some fancy code. Suggest making test() be in a class with a boolean, pass that class to the Timer Task constructor, which you will subclass Timer Task to do that. Then set the Timer to run at sixty seconds after starting. If test() does not run in a loop and extend Thread, basically what we have here is better approached with Barrier, but the design of that precludes soft-spin loops.
I could give you some clues but would lead to bad design unless used properly.
Write test cases, and be sure to run them.
-
Implement a Timeout
I found this forum page with this question because I had almost the same question, and then figured out a pretty nice way of doing this today (based on Brian Goetz's Concurrency in Practice book), which I think is quite elegant, so wanted to share...
So assume that I have a method SomeClass.someMethod() that returns instanece of SomeOtherClass on which I want to implement a timeout on.
public class MyCallingClass {
private static final int TIMEOUT_MILLIS = 5000L; // 5 seconds
private class TimedWrapper implements Callable<SomeOtherClass> {
private SomeClass someClass;
public TimedWrapper(SomeClass someClass) { this.someClass = someClass; }
public SomeOtherClass call() throws Exception {
return someClass.someMethod();
}
}
private ExecutorService executor = Executors.newSingleThreadExecutor();
public void myCallingMethod(SomeClass someClass) {
long end = System.currentTimeMillis() + TIMEOUT_MILLIS;
Future<SomeOtherClass> f = executor.submit(new TimedWrapper(someClass));
try {
return f.get(end, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw e;
} catch (TimeoutException e) {
f.cancel(true);
}
}
}
HTH
Sujit