Home > database >  java.util.concurrent.Future.get() method gets stuck and program doesn't terminate
java.util.concurrent.Future.get() method gets stuck and program doesn't terminate

Time:09-23

I was trying to follow a Java Concurrency tutorial. When I run this program, it gets stuck. Can someone help me understand why?

public class App 
{
    public static void main( String[] args ) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // Submit a task and accept the placeholder object for return value
        Future<Integer> future = executorService.submit(new Task());

        try {
            Integer result = future.get();
            System.out.println("Result from the task is: "   result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    static class Task implements Callable<Integer> {
        @Override
        public Integer call() {
            return new Random().nextInt();
        }
    }
}

CodePudding user response:

It's "stuck" because you never shut down the executor. By design, the executor is going to be alive and wait for new work to come in. Because no work is going to come in, the executor will persist until...well...indefinitely.

In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new work to do.

...[O]n the other hand, an app could reach its end but not be stopped because a waiting ExecutorService will cause the JVM to keep running.

So, let's shut it down, shall we?

// At the tail end of your try-catch
} finally {
    executorService.shutdown();
}

CodePudding user response:

You need to shutdown the ExecutorService

executorService.shutdown();
  • Related