0

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.

enter image description here

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.

eg: enter image description here

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));

    }
}
4
  • 1
    as the Exception is passed on, the executor service is not shut down and it is using a non-daemon Thread. Doc of newFixedThreadPool: "The threads in the pool will exist until it is explicitly shutdown". Use (create) a ThreadFactory that create daemon Threads or (better IMO) use try-finally to always shut down Commented Mar 18, 2021 at 18:29
  • ` executorService.shutdownNow();` is called in the code if you see. Commented Mar 18, 2021 at 18:34
  • You must be able to catch the thread interruption in the main method and that should exit the application. Commented Mar 18, 2021 at 18:34
  • additionally, I saw that it goes in uncaughtException method of threadgroup, there it prints stacktrace and moves ahed if it does not see instanceof ThreadDeath Commented Mar 18, 2021 at 18:36

1 Answer 1

1

The TimeoutException is not being caught in main, so main is also terminating abruptly without calling shutdownNow. The main thread is terminated but the threads created by Executors are non-daemon by default, so the virtual machine is not shut down, the Executors thread(s) continue running.

Solution:

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        try {
            workWithFutureCallable(executorService);
        } finally {
            executorService.shutdownNow();
        }
    }

or

implement a ThreadFactory to create daemon threads and use it to get the service:

        ExecutorService executorService = Executors.newFixedThreadPool(2, r -> {
            var thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        });

Even better, at least in production code, catch and handle the Exceptions (together with the finally block.)

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @user15244370 , I am sorry, I could not understand same thing via your comments. I added finally block and it worked. Indeed, I did not think that threads created by executorservice are non-daemon threads. Thank you very much. Also, here I am studying about concurrency, so yes, production grade code will handle and will also note that shutdown of executorservice should be in finally block only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.