Reputation: 155
I want to call a method in java which blocks for some reason. I want to wait for the method for X minutes and then I want to stop that method.
I have read one solution here on StackOverflow which gave me a first quick start. I am writing that here :-
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}
But now my problem is, my function can throw some Exception which I have to catch and do some task accordingly. So if in code the function blockingMethod() thorws some exception how do I catch them in Outer class ?
Upvotes: 1
Views: 2503
Reputation: 31
In the ExecutionException
catch block: e.getCause()
https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause
Upvotes: 1
Reputation: 46209
You have everything set up to do that in the code you provide. Just replace
// handle other exceptions
with your exception handling.
If you need to get your specific Exception
you get it with:
Throwable t = e.getCause();
And to differentiate between your Exceptions you can do like this:
if (t instanceof MyException1) {
...
} else if (t instanceof MyException2) {
...
...
Upvotes: 4
Reputation: 3651
thread.sleep(x millisecods) will stop the thread for x milliseconds, then it will resume. The other way to do it is to call thread.wait(x) (with a timeout value for x) and then call thread.notify() to "wake" the sleeping thread.
Upvotes: -1