Skip to content

Commit

Permalink
Starts using Future for background tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
fathzer committed Nov 23, 2024
1 parent f3522cf commit 85010e0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<dependency>
<groupId>com.fathzer</groupId>
<artifactId>games-core</artifactId>
<version>0.0.11-SNAPSHOT</version>
<version>0.0.12-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
Expand Down
54 changes: 54 additions & 0 deletions src/test/java/com/fathzer/jchess/uci/util/FutureTricks.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.fathzer.jchess.uci.util;

import static org.junit.jupiter.api.Assertions.*;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;

import com.fathzer.games.util.exec.CustomThreadFactory;

class FutureTricks {
private Thread currentThread;
// private static class MyCoolTask implements Callable()

@Test
void test() throws InterruptedException, ExecutionException {
final ThreadFactory threadFactory = new CustomThreadFactory(() -> "executorService", true);
ExecutorService svce = Executors.newSingleThreadExecutor(threadFactory);
Callable<String> task = () -> {
try {
currentThread = Thread.currentThread();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "I was interrupted";
}
return "Normal";
};

Future<String> future = svce.submit(task);
assertEquals("Normal", future.get());

future = svce.submit(task);
Awaitility.await().atLeast(100, TimeUnit.MILLISECONDS);
currentThread.interrupt();
Awaitility.await().atLeast(100, TimeUnit.MILLISECONDS);
assertEquals("I was interrupted", future.get());

future = svce.submit(task);
Awaitility.await().atLeast(100, TimeUnit.MILLISECONDS);
future.cancel(true);
Awaitility.await().atLeast(100, TimeUnit.MILLISECONDS);
assertEquals("I was interrupted", future.get());

}

}

0 comments on commit 85010e0

Please sign in to comment.