未来与可完成的未来?对于这个用例 Completablefuture 会有什么不同吗?

Future vs Completablefuture ? for this use case Completablefuture will make any difference?

我有四个服务。

One will give hotels which is matching to the query.
One will give City which is matching to the query.
One will give Airports which is matching to the query.
One will give Metro stations which is matching to the query.

对于每个 HTTP 请求,我将点击这四个服务并将来自四个服务的响应合并 return。

所以我的示例代码就像

for(EntityGroups entityGroups: EntityGroups.values()){
            Callable<Response> callable = new XCallable(entityTypetoFetch, searchQuery);
            Future<List<Entity>> listFuture = executor.submit(callable);
            entityTypeAndFutureMap.put(entityTypetoFetch, listFuture);
        }

在此之后,我在 for 循环中得到所有响应

trainStationList = entityTypeAndFutureMap.get(EntityGroups.TRAIN_STATION).get();
            landmarkEntities = entityTypeAndFutureMap.get(EntityGroups.LANDMARK_GROUP).get();
            cityEntities = entityTypeAndFutureMap.get(EntityGroups.CITY_GROUP).get();
            hotelEntities = entityTypeAndFutureMap.get(EntityGroups.HOTEL_GROUP).get();

因为我希望所有列表合并并做出最终响应。我正在打一个阻塞电话。我只想合并这些列表和 return。 如果我在这里使用completablefuture,会有帮助吗?

截至目前,随着 TPS 的增加,我的 CPU 使用率非常高。 增加机器有帮助,但仍然有任何优化的方法来解决这个问题吗?

A CompletableFuture 具有一些常规 Future 所没有的功能特性,例如使用 thenApplythenAccept 链接执行的能力在结果可用后对其进行处理。您还可以通过调用 CompletableFuture.

complete() 方法从另一个线程完成 CompleteableFuture

所以在你的情况下,这取决于你想对结果做什么。如果您在进一步的程序流程中需要结果,则必须像使用 get() 方法一样等待它。由于 Futures 将在创建后立即执行,因此它们将 运行 在工作线程上并行执行,并且顺序等待它们并不意味着它们将 运行 顺序地执行。

但是如果您不需要进一步处理结果(例如,您只想将结果插入数据库),CompletableFuture 的优势在于您可以提供一个获取结果的函数并用它做点什么。例如。像这样 completableFuture.thenAccept(result -> DB::storeInDB); 这样你就不必等待 get().

的结果