Created
July 25, 2017 01:31
-
-
Save am4dr/c22b1c55a95673eedf113040330a2c2c to your computer and use it in GitHub Desktop.
cancelling CompletableFuture
This file contains hidden or 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
| import java.util.concurrent.FutureTask | |
| import java.util.concurrent.CompletableFuture | |
| import java.util.concurrent.Callable | |
| import java.util.concurrent.CancellationException | |
| // 指定時間寝て、夢見SCOREを返す | |
| int dream(int millis) { | |
| try { | |
| println "$millis ms 寝る..." | |
| Thread.sleep(millis) | |
| println "よく寝た~" | |
| def c = 5; | |
| def b = (0..<c).collect { Math.random() }.sum() / (double)c | |
| return 100 * (1 - Math.pow(1.7, -b * millis / 1000.0)) | |
| } | |
| catch(InterruptedException e) { | |
| println "途中で起こされた!!" | |
| return Integer.MIN_VALUE | |
| } | |
| } | |
| def a () { | |
| def future = CompletableFuture.supplyAsync { dream(3000) }.thenAccept { println "Yumemi score: $it" } | |
| return future | |
| } | |
| def b() { | |
| def task = new FutureTask({ dream(3000) } as Callable) | |
| def future = CompletableFuture.supplyAsync { task.run(); task.get() }.thenAccept { println "Yumemi score: $it" } | |
| future.exceptionally { e -> if (e instanceof CancellationException) task.cancel(true) } | |
| return future | |
| } | |
| println "- a ----------------" | |
| a().get() | |
| println "- b ----------------" | |
| b().get() | |
| println "- cancel a ---------" | |
| a().cancel(true); sleep(3500); | |
| println "- cancel b ---------" | |
| b().cancel(true); sleep(3500); |
This file contains hidden or 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
| - a ---------------- | |
| 3000 ms 寝る... | |
| よく寝た~ | |
| Yumemi score: 48 | |
| - b ---------------- | |
| 3000 ms 寝る... | |
| よく寝た~ | |
| Yumemi score: 60 | |
| - cancel a --------- | |
| 3000 ms 寝る... | |
| よく寝た~ | |
| - cancel b --------- | |
| 3000 ms 寝る... | |
| 途中で起こされた!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment