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)