Reputation: 944
Assuming I have the following code snippet:
FutureTask<?> f = new FutureTask<>(() -> { Thread.sleep(5000); return 1 + 2; })
myExecutor.execute(f);
f.get(3, TimeUnit.SECONDS);
From what is coded, the last line will fail after 3 seconds with java.util.concurrent.TimeoutException
My question is: Does the actual work inside future continue to get executed? Or it does it get cancelled? Could I, later, after another 2 seconds, retrieve the actual result, or is it gone?
Upvotes: 1
Views: 567
Reputation: 38910
Does the actual work inside future continue to executed?
Yes.The task execution will be in progress unless you cancel it.
Or it does it get cancelled?
No. It won't cancelled unless you cancel it.
Could I, later, after another 2 seconds, retrieve the actual result, or is it gone?
Yes. You can get result later even after time-out.
Have a look at sample code snippet:
Below code get the status of future after 3 seconds time-out. I have created artificial delay to demonstrate the example. In real time, the output will be different in absence of sleep()
methods.
public class FutureTaskQuery {
public static void main(String args[]){
ExecutorService executor = Executors.newFixedThreadPool(1);
Future future = executor.submit(new MyCallable());
try{
Integer result = (Integer)future.get(3000, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
System.out.println("Time out after 3 seconds");
//future.cancel(true);
}catch(InterruptedException ie){
System.out.println("Error: Interrupted");
}catch(ExecutionException ee){
System.out.println("Error: Execution interrupted");
}
try{
Thread.sleep(4000);
Integer result = (Integer)future.get(2000, TimeUnit.MILLISECONDS);
System.out.println("Result:"+result);
}catch(Exception err){
err.printStackTrace();
}
executor.shutdown();
}
}
class MyCallable implements Callable<Integer>{
public Integer call(){
try{
Thread.sleep(5000);
}
catch(Exception err){
err.printStackTrace();
}
return 2;
}
}
output:
Time out after 3 seconds
Result:2
If you un-comment below line
future.cancel(true);
output:
Time out after 3 seconds
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at MyCallable.call(FutureTaskQuery.java:31)
at MyCallable.call(FutureTaskQuery.java:28)
Upvotes: 0
Reputation: 8200
It continues to be executed.
By adding a second f.get(3, TimeUnit.SECONDS);
you can retrieve the result:
Object o2 = f.get(3, TimeUnit.SECONDS);
System.out.println("o2 = " + o2); // prints o2 = 3
You can try to cancel the calculation by calling
f.cancel(true);
Then, when retrieving the object with
Object o2 = f.get(3, TimeUnit.SECONDS);
it throws a CancellationException
Upvotes: 2