public < T > T callWithTimeout ( Callable < T > callable , long duration , TimeUnit unit ) throws Exception { Future < T > future = executor . submit ( callable ) ; try { return future . get ( duration , unit ) ; } catch ( InterruptedException e ) { future . cancel ( true ) ; throw e ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause == null ) { cause = e ; } if ( cause instanceof Exception ) { throw ( Exception ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } throw e ; } catch ( TimeoutException e ) { future . cancel ( true ) ; throw new UncheckedTimeoutException ( e ) ; } }
Invokes a specified Callable timing out after the specified time limit . If the target method call finished before the limit is reached the return value or exception is propagated to the caller exactly as - is . If on the other hand the time limit is reached we attempt to abort the call to the Callable and throw an exception .