I have four Services.
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.
For each HTTP request, I will hit these four services and merge the response from four of the service and return.
So my Sample code is like
for(EntityGroups entityGroups: EntityGroups.values()){
Callable<Response> callable = new XCallable(entityTypetoFetch, searchQuery);
Future<List<Entity>> listFuture = executor.submit(callable);
entityTypeAndFutureMap.put(entityTypetoFetch, listFuture);
}
After this I get all response in for loop
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();
As I want all the list to merge and make the final response. I am making a blocking call. I just want to merge these list and return. If I use completablefuture here, will it help?
As of now my CPU uses goes very high as I increase the TPS. increasing machines is helping, but still is there any optimized way to solve this?
A CompletableFuture
has some functional features that a regular Future
does not have, like the ability to chain executions with thenApply
or thenAccept
that take a function that process the result after it´s available. You also can complete a CompleteableFuture from another Thread by calling the complete()
method of the CompletableFuture
.
So in your situation it depends on what you want to do with the result. If you need the result in the further program flow, you have to wait for it like you do with the get()
method. Since Futures will be executed as soon as they are created they will run in parallel on a Worker-Thread, and waiting for them sequentially does not mean they will run sequentially.
But if you do not need the results for further processing (Eg. you just want to insert the results in a Database) a CompletableFuture
will have the advantage that you can provide a function that takes the result and does something with it. Eg. like this completableFuture.thenAccept(result -> DB::storeInDB);
This way you would not have to wait for the result with get()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With