Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScheduledExecutorService: when shutdown should be invoked?

I use ScheduledExecutorService in my application. I need to use it from time to time in certain Utility class to run scheduled threads.

Is it a good design to hold ScheduledExecutorService in static field? Is it a must to invoke ScheduledExecutorService.shutdown() in such case? What is the risk if I do not invoke shutdown?

That's what I thought to do:

private static ScheduledExecutorService exec = Executors.newScheduledThreadPool(5);

public void scheduleTask(String name) {
        Future<?> future = futuresMapping.get(name);
        if(future!=null && !future.isDone())
            future.cancel(true);

        //execute once   
        Future<?> f = scheduledExecutor.schedule(new MyTask()), 1, TimeUnit.MINUTES);
        futuresMapping.put(name, f);
}

Thank you

like image 849
lili Avatar asked Mar 29 '12 13:03

lili


People also ask

Is it necessary to shutdown ExecutorService?

When finished using an ExecutorService , you need to shut it down explicitly. From its javadoc: "An unused ExecutorService should be shut down to allow reclamation of its resources." Calling shutdown initiates a gradual and orderly shutdown.

How do I shut down ExecutorService gracefully?

Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.

What will happen to the non terminated future objects if the executor is shutdown?

Using shutdown() and awaitTermination​() In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new tasks to come. It simply means that JVM will not terminate if we are expecting it to.


1 Answers

You should always invoke shutdown() or shutdownNow(). If you don't do that your application might never terminate as there are still threads active (depending how you're terminating your app, whether it's in managed environment or not etc.).

Usually you would call shutdown() from some sort of lifecycle event method - such as from Spring's DisposableBean.destroy(), or if you're not using any framework just call it before exiting from your app.

like image 57
maximdim Avatar answered Sep 28 '22 18:09

maximdim