O
O
Oleg Mikhailov2019-01-22 12:58:53
Java
Oleg Mikhailov, 2019-01-22 12:58:53

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();

How can this be done asynchronously in this place, without blocking the main processing thread with this action, because at this moment, more requests come to this controller and the thread should be temporarily released until the result from these http responses is received and the execution of the logic continues?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Oleg Mikhailov, 2019-02-13
@Olegatorapp

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 лежат уже все ответы, а время на выполнение всех запросов будет таким, 
                       //сколько займёт самый долгий ответ
                });

D
Dmtm, 2019-02-01
@Dmtm

why requests are executed in the controller and not in the CompletableFuture itself?
something like this:
CompletableFuture.supplyAsync(...)
.exceptionally(....)
.thenApply(....)
.thenAccept(....);

Y
Yerlan Ibraev, 2019-01-22
@mad_nazgul

Future?!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question