-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Starts using Future for background tasks
- Loading branch information
Showing
2 changed files
with
55 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
src/test/java/com/fathzer/jchess/uci/util/FutureTricks.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
|
||
} | ||
|
||
} |