Created
May 5, 2018 16:47
-
-
Save milovtim/e1eabcbead542815fc95deae388ef036 to your computer and use it in GitHub Desktop.
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
import groovy.transform.Canonical | |
import java.util.concurrent.CompletableFuture | |
import java.util.function.Function | |
import java.util.function.Supplier | |
final long serviceExecutionTime = 1000 | |
def rand = new Random() | |
def initVal = rand.nextInt(100) | |
@Canonical | |
class RpcResult { | |
Integer val | |
Throwable error | |
} | |
//remote service call emulation | |
def rpcServiceSupplier = {Integer arg -> | |
return { | |
sleep(serviceExecutionTime) | |
if (arg == 3) throw new IllegalArgumentException("Invalid arg=$arg") | |
new RpcResult(val: arg * initVal) | |
} as Supplier<RpcResult> | |
} | |
def args = 1..10 //some remote service call arguments | |
def futures = args | |
.collect { rpcServiceSupplier(it) } | |
.collect { | |
CompletableFuture | |
.supplyAsync(it) | |
.exceptionally { err -> new RpcResult(error: err)} | |
} | |
def result = CompletableFuture.allOf(futures as CompletableFuture[]) | |
.thenApply { | |
futures.collect { it.join() } | |
} | |
println result.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment