0

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?

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315
  • Try CompletionService: http://stackoverflow.com/questions/19348248/waiting-on-a-list-of-future – Christopher Yang Sep 14 '15 at 19:11
  • Thanks , is this something that can be used in conjunction with Spring's @Async? – Punter Vicky Sep 14 '15 at 19:16
  • Thanks , this is very helpful. – Punter Vicky Sep 14 '15 at 19:42
  • I don't think CompletionService is best choices for this scenario —— cause it's purpose is "get the fisrt returned result as soon as possiable"。 In this question's scenario, he needs "waiting for all threads returned, then decided what to do". So I think ExecutorService.invokeAll() would be best choice. Am I possiablly right? – watchzerg Dec 30 '15 at 10:01

1 Answers1

2

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());
Christopher Yang
  • 3,769
  • 4
  • 30
  • 27
  • Thanks Christopher , this does answer my original question. However when I saw the link provided by you , I saw that CompletionService is a better option as I can handle scenarios returning error better. Please let me know if my understanding is not correct. – Punter Vicky Sep 14 '15 at 20:45
  • CompletionService is definitely the better approach. But If the async calls aren't so expensive and the failure rate will be low, I feel there's nothing wrong with waiting for the results one by one. – Christopher Yang Sep 14 '15 at 21:32
  • Thanks A lot , Chris! – Punter Vicky Sep 17 '15 at 11:03