I am trying a java program to understand working of Future.
I wrote following program and it never ends. If I put a value that is less than 10 in Thread.sleep(), then it works but not for values >=10.
I understood the part that is causing problem is probably the future.get call.
However, on further analysis, what I tried was, to handle all the exceptions and not letting jvm handle them.
Now it terminated fine.
I did a further check and saw that if I throw ExecutionException and InterruptedException and handle TimeoutException it works fine again.
Here strange part is I have to compulsorily handle TimeoutException, else it will not work. I am not so sure why this strange behaviour persists.
I am using OpenJDK 15.
If anybody wants to try code snippet its here:
import java.util.concurrent.*;
public class FixedThreadPoolExecutorDemo2 {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
workWithFutureCallable(executorService);
executorService.shutdownNow();
}
private static void workWithFutureCallable(ExecutorService executorService) throws ExecutionException, InterruptedException, TimeoutException {
Future<Integer> myOtherFuture = executorService.submit(() -> {
try {
Thread.sleep(109);
} catch (InterruptedException e) {
}
return 1000;
});
System.out.println("myOtherFuture should be cancelled if running for more than specified time. ->" + myOtherFuture.get(10, TimeUnit.MILLISECONDS));
}
}


newFixedThreadPool: "The threads in the pool will exist until it is explicitly shutdown". Use (create) aThreadFactorythat create daemonThreads or (better IMO) usetry-finallyto always shut downThreadDeath