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 ?
catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }