[英]Cancelling a task scheduled in a ScheduledExecutorService keeps executor alive
這已經困擾了我幾個小時。如果我安排一個任務在5秒鍾內執行,然后立即取消該任務,我希望“ awaitTermination”方法立即返回,但它會阻塞7秒鍾 (不是五個)
這是一個在Java 11上重現該問題的JUnit 5測試用例。
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");
}
}
有任何想法嗎?
您不會在executorService上調用shutdown或shutdownNow,因此可以永遠等待。 它永遠不會終止。 首先調用shutdown,然后單元測試應該工作。
scheduled.cancel(false);
executorService.shutdown(); // This was missing
if (!executorService.awaitTermination(7, TimeUnit.SECONDS)) {
...
awaitTermination “阻塞,直到關閉請求后所有任務完成執行,或者發生超時,或者當前線程被中斷(以先發生者為准)”(從注釋中復制,謝謝ptomli)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.