Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milovtim/e1eabcbead542815fc95deae388ef036 to your computer and use it in GitHub Desktop.
Save milovtim/e1eabcbead542815fc95deae388ef036 to your computer and use it in GitHub Desktop.
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