I have this frustrating issue: I am trying to see if TimeoutException is thrown in below code, but that doesn't happen ever. It always prints the current time 5 times and finishes.
class MyTask1 implements Callable<Void> {
public Void call() throws Exception {
for (int i=0; i < 5; i++) {
System.out.println(new java.util.Date());
Thread.sleep(1000);
}
return null;
}
}
public class Timeout {
public static void main(String[] args) throws Exception {
FutureTask<Void> futureTask = new FutureTask<Void>(new MyTask1());
futureTask.run();
try {
futureTask.get(1000, TimeUnit.MILLISECONDS); // Check if FutureTask completed in the given time
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
futureTask.cancel(true);
e.printStackTrace();
}
}
}
I am using Thread.sleep(1000)
so that call()
method takes at least 5 seconds (as it is done 5 times using a for loop). And I am calling get()
method by setting timeout value 1 second.
But why doesn't it throw TimeoutException?
This could be a possible duplicate of How do I get FutureTask to return after TimeoutException?
But appriciate if someone can help as this is really frustrating. Or I didn't understand how to use the FutureTask to handle the timeout?