我目前有一个流畅的构建器,例如
SomeObject someObject = new SomeObject.Builder()
.field1(someWebService.getSomeValue())
.field2(someOtherService.getSomething())
.field3(anotherService.youGetThePicture())
// etc x 10
.createSomeObject()
我想优雅地将其转换为并行运行,以便三个服务调用可以同时运行。这可能吗?我使用的是 Java 8,因此流是一个选项。
谢谢。
最佳答案
好吧仅供引用你想做的可以这样完成
SomeObject.Builder someObject = new SomeObject.Builder();
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> someObject.field1(someWebService.getSomeValue());
CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> someObject.field2(someOtherService.getSomething());
...
SomeObject res = CompletableFuture.allOf(cf1, cf2, ...).get().createSomeObject();
但我强烈建议您改为异步调用服务,收集响应,然后同步构建对象。
如果您想使用流来执行此操作,您应该将所有 lambda(服务调用)添加到集合中,然后使用 serviceCalls.stream().parallel().forEach(Consumer::accept);
但这也不好
关于java - 将 Fluent 构建器转换为并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659853/