Executor Service – Shutdown

The below code is used to create an ExecutorService instance and submit the Callable task. So the code added inside of the method call() will be called asynchronously. Initially I did not add the awaitTermination time. So the code was working fine but after some I noticed that the method was not called actually.

After careful analysis, I found out that the Executor Service shutdown immediately and it did not wait for the submitted tasks to be completed. To resolve this, we should have to inform Executor Service to wait/block for some time. We can achieve this by calling awaitTermination on the ExecutorService and passing the wait time


  public void asyncProcess(){
       
        Callable callable = new Callable() {
            @Override
            public void call() throws Exception {
             //Method to call async
            }
        };
        FutureTask future = new FutureTask<>(callable);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(future);
        executorService.shutdown();
        try {
            // Wait until all tasks are finished. Waiting time is 1 min
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            LOGGER.error("Exception happened while waiting for the termination of the tasks",e);
        };
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s