Answer the question
In order to leave comments, you need to log in
How to execute part of a method asynchronously?
I will immediately describe the structure with which we are dealing:
1. There is an asynchronous controller (with a dedicated THREAD_POOL_EXECUTOR) that returns a CompletableFuture.
2. Logic is executed inside this controller and in the middle of this execution it is necessary to send, for example, 5 http requests, get their result and continue to execute the controller logic.
There is a problem in the place where these requests are sent - everything is executed very slowly.
Sending here:
RequestSendManager manager = new RequestSendManager();
DeferredResult<Map<BaseProtocol, RequestData>> res = manager
.sendToPool(dspDatas);
Map<BaseProtocol, RequestData> result =
(Map<BaseProtocol, RequestData>) res.getResult();
Answer the question
In order to leave comments, you need to log in
For those who are interested, the problem is solved as follows:
ExecutorService pool = Executors.newFixedThreadPool(dspMap.size());
List<Callable<BaseProtocol>> todo = new ArrayList<>(5);
dspMap.forEach((name, httpRequest) -> {
todo2.add(() -> httpRequest.send());
});
try {
List<Future<BaseProtocol>> res = pool.invokeAll(todo2);
res.forEach(v -> {
//тут в res лежат уже все ответы, а время на выполнение всех запросов будет таким,
//сколько займёт самый долгий ответ
});
why requests are executed in the controller and not in the CompletableFuture itself?
something like this:
CompletableFuture.supplyAsync(...)
.exceptionally(....)
.thenApply(....)
.thenAccept(....);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question