简体   繁体   中英

Cancelling a task scheduled in a ScheduledExecutorService keeps executor alive

This has been bugging me for a few hours now.. If I schedule a task to be executed in 5 seconds and then cancel that task immediately I would expect the "awaitTermination" method to return immediately, but it keeps blocking for the full 7 seconds (not five)..

Here is a JUnit 5 test case that reproduces the issue on Java 11.

package dummy;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;

class DummyTest {

  @Test
  @DisplayName("Cancelling task should work...")
  void cancel_task() throws InterruptedException {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    AtomicBoolean isExecuted = new AtomicBoolean(false);
    ScheduledFuture<?> scheduled = executorService.schedule(() -> isExecuted.set(true), 5, TimeUnit.SECONDS);
    scheduled.cancel(false);

    if (!executorService.awaitTermination(7, TimeUnit.SECONDS)) {
      fail("Didn't shut down within timeout"); // <-- Fails here
    }

    assertFalse(isExecuted.get(), "Task should be cancelled before executed");
  }

}

Any ideas?

You don't call shutdown or shutdownNow on your executorService, so you can wait forever. It will never terminate. Call shutdown first, then the unit test should work.

scheduled.cancel(false);
executorService.shutdown(); // This was missing
if (!executorService.awaitTermination(7, TimeUnit.SECONDS)) {
...

awaitTermination "Blocks until all tasks have completed execution after a shutdown request , or the timeout occurs, or the current thread is interrupted, whichever happens first" (copied from comments, thanks ptomli).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM