I'm wondering if there is a way to shutdown a Java ExecutorService
and 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