Filipe Miranda Filipe Miranda - 1 month ago 12
Java Question

In Java FutureTask if the task Times out, doe the Task get Cancelled?

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 it 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 executed? Or it gets cancelled? Could I later, after another 2 seconds retrieve the actual result, or is it gone?

Answer

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