Filipe Miranda Filipe Miranda - 8 months ago 33
Java Question

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

Assuming I have the following code snippet:

FutureTask<?> f = new FutureTask<>(() -> { Thread.sleep(5000); return 1 + 2; })

f.get(3, TimeUnit.SECONDS);

From what is coded, the last line will fail after 3 seconds with

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?


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


Then, when retrieving the object with

Object o2 = f.get(3, TimeUnit.SECONDS);

it throws a CancellationException