取消ScheduledExecutorService中安排的任务可使执行程序保持活动状态

问题描述 投票:1回答:1

这已经困扰了我几个小时了。如果我安排一个任务在5秒内执行然后立即取消该任务我会期望“awaitTermination”方法立即返回,但它会持续阻塞整整7秒(不是五个)..

这是一个JUnit 5测试用例,它在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");
  }

}

有任何想法吗?

java scheduledexecutorservice
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.