Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown Java Executor After All Submitted Tasks Finished Without Blocking

I'm wondering if there is a way to shutdown a Java ExecutorServiceand allow all submitted tasks to finish while not blocking.

to be more specific, I want to schedule a Runnable with a delay and continue with the code, without the need to keep a reference to the ExecutorService to be able to shut it down.

The following code will terminate the submitted task as it hasn't started yet:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdown();
...

While this code will block until the task is finished:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
...

I want to have something like this:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
executor.shutdownAfterTerminationWithoutBlocking();
...
code that runs without waiting

I know this possible using Timer but i'm wondering if this is possible using ExecutorService

like image 933
zuckermanori Avatar asked May 17 '16 13:05

zuckermanori


People also ask

Does Executor service shutdown automatically?

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.

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 you stop an Executor in Java?

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.

How do I shut down ExecutorService gracefully?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.


1 Answers

ExecutorService.shutdown javadoc says:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

So tasks that already submitted, but not yet started, will be executed. Exactly as you need.

like image 100
Nikem Avatar answered Nov 03 '22 22:11

Nikem