frostmann frostmann - 2 months ago 4
Java Question

Why does the program wait for the schedule() to finish but doesn't wait for the scheduleWithFixedDelay()?

Here's the code:

ScheduledExecutorService service = null;
try {
service = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = () -> System.out.println("Executed only once");
Runnable task2 = () -> System.out.println("Executed repeatedly");

service.schedule(task1, 5, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(task2, 6, 2, TimeUnit.SECONDS);
} finally {
if (service != null) {

When executing the above code the program waits 5 seconds to run schedule() but after that it finishes without running the scheduleWithFixedDelay().

I suspect the reason is that schedule() is executed synchronously unlike the scheduleWithFixedDelay() but I haven't found the arguments in favor of this in the docs.


This is a bit subtle, but I think the answer lies in the wording of the documentation for shutdown:

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

Your first task qualifies as a “previously submitted task,” so shutdown() waits for it to execute.

Technically, the repeating task was previously submitted, but since it repeats forever, waiting for it complete is impossible. Attempting to do so would violate the contract of shutdown(). So, I would say that the only alternative is to ignore future executions of repeating tasks.