7

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

zuckermanori
  • 1,675
  • 5
  • 22
  • 31
  • Your first example does what you want - by default the scheduled tasks are *not* cancelled upon shutdown. This is a setting that can be changed. – assylias May 17 '16 at 13:36
  • Add your "code that runs without waiting" as another task and shutdown after termination as normal – Lev Kuznetsov May 17 '16 at 13:36

1 Answers1

9

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.

Nikem
  • 5,716
  • 3
  • 32
  • 59
  • Thank you Nikem. The next line in this javadoc says: "This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that." And so I thought it will shutdown the executor without waiting. Apparently it'll just not wait for the tasks to finish. – zuckermanori May 17 '16 at 13:58
  • 1
    Yes, it is not a blocking operation. It essentially just marks executor services as awaiting termination and returns right away. – Nikem May 17 '16 at 19:18