Async tasks cancellation fix (#907)

This commit is contained in:
Konstantin Shandurenko 2022-04-11 21:26:59 +03:00 committed by GitHub
parent 1bb0af7f77
commit 2cea7ca5af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 1 deletions

View File

@ -79,7 +79,12 @@ final class SchedulerImpl implements Scheduler {
// By either adding the task to the execution queue or submitting it to the pool
switch (task.executionType()) {
case SYNC -> taskQueue.offer(task);
case ASYNC -> EXECUTOR.submit(() -> handleTask(task));
case ASYNC -> EXECUTOR.submit(() -> {
if (!task.isAlive()) {
return;
}
handleTask(task);
});
}
}

View File

@ -2,6 +2,7 @@ package net.minestom.server.timer;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
@ -66,6 +67,22 @@ public class TestScheduler {
assertFalse(result.get(), "Task should be cancelled");
}
@Test
public void cancelAsyncDelayedTask() throws InterruptedException {
Scheduler scheduler = Scheduler.newScheduler();
AtomicBoolean result = new AtomicBoolean(false);
var task = scheduler.buildTask(() -> result.set(true))
.delay(Duration.ofMillis(1))
.executionType(ExecutionType.ASYNC)
.schedule();
assertTrue(task.isAlive(), "Task should still be alive");
task.cancel();
assertFalse(task.isAlive(), "Task should not be alive anymore");
scheduler.process();
Thread.sleep(10L);
assertFalse(result.get(), "Task should be cancelled");
}
@Test
public void parkTask() {
Scheduler scheduler = Scheduler.newScheduler();