Home > database >  Executor Service isDone() behavior
Executor Service isDone() behavior

Time:09-27

I'm new to learning Java multithreading. I started with this simple code but it seems that submitResults.isDone() never returns true.

I'm expecting that "Task Executed" should be printed as a result but I get an empty console.

Here is my simple class:

public class FuturesExample {

    public static void main(String[] args) {

        FuturesExample.executeThreadScheduler();
    }

    static void executeThreadScheduler()
    {
        ExecutorService service = Executors.newFixedThreadPool(10);
        Callable<String> callableTask = ()->{
            TimeUnit.MILLISECONDS.sleep(300);
            return "Task Executed" ;
        };

        Future<String> submitResults = service.submit(callableTask);

            try {
                if(submitResults.isDone())

                {
                    System.out.println(submitResults.get());
                }
                service.shutdown();
                if(!service.awaitTermination(800,TimeUnit.MILLISECONDS))
                {
                    service.shutdownNow();
                }
            } catch (InterruptedException e) {
                service.shutdownNow();
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }


    }

CodePudding user response:

You're not waiting for the task to be completed hence the submitResults.isDone() returns false and code terminates. Call submitResults.get() before the if condition, it will block the execution of the code until the callable completes its execution and you'll see that "Task Executed" will be printed. More info can be found here and here

CodePudding user response:

When you call submitResults.isDone() your callableTask has not completed yet, and so isDone() returns false. Since your condition returns false, you don't execute your print statement, and so you won't see "Task Executed" even when your task completes.

To wait until the task has completed, remove the call to isDone(), and just rely on submitResults.get() to block until the task completes.

 Future<String> submitResults = service.submit(callableTask);

     try {
         System.out.println(submitResults.get());
         service.shutdown(); // ...
  • Related