简体   繁体   中英

Spring Async Task returning Future

I am developing a Service that calls multiple external services that are independent of each other. I collate the responses of all these services and return it as a consolidated response. Since these are not interdependent , I am using Spring's @Async capability to perform all these activities in parallel. I am following the example provided in this link

https://spring.io/guides/gs/async-method/

Here , a while loop is used to wait until all the responses are obtained -

    while (!(page1.isDone() && page2.isDone() && page3.isDone())) {
        Thread.sleep(10); //10-millisecond pause between each check
    }

I know this a sample code which was aimed at explaining the concept, which it does effectively. However in an enterprise application , can a while loop be used similar to what is shown above or should a different approach be adopted? If a different approach has to be adopted what is the advantage of the approach over using a while loop?

Couldn't you just use Future.get()? It's a blocking call. It'll make sure to wait until the result is ready. You can do something like:

List<Future<?>> results = Lists.newArrayList();
results.add(page1.get());
results.add(page2.get());
results.add(page3.get());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM