Calling various web services in parallel with Webapp

We have a web style app (java) that needs to be made from about 15 different webserivce calls from one method. For instance: ...

public Resolution userProfile() { serviceOneCall(); serviceTwoCall(); serviceThreeCall(); serviceFourCall(); .... serviceTenCall(); return new RedirectResolution("profiel.jsp"); } 

All of them can be called in parallel and are independent of each other. The only thing that most of these calls make is to put data in a session, and one or two can put data in the same object as in the session, so the problem with threads is probably related to this.

Can anyone suggest a good way to trigger all this at the same time?

+4
source share
3 answers

All solutions for parallel work are associated with the emergence of new threads or sending jobs to the thread pool for remote network calls.

A good way to avoid thread safety issues is to use the executorService and subclass Callable<T> (to submit(Callable) or invokeAll(Collection<Callable>) ), and Callables will return a response value. That way, your original method can simply handle the return values โ€‹โ€‹of each call and choose to set responses in the session or update other objects, rather than this work happening in another thread.

So, the basic algorithm:

  • Send each of these calls to the executor Callable<T> in Callable<T> subclasses
  • Build the Future<T> , which you will return from the executorService function
  • Call Future.get() for each block until you get a response, and then process the answers, but you want to return to the main thread
+5
source

Use an ExecutorService with a thread pool to send a Callable for each WS you need to call, and synchronize an object that updates when there is a chance of a simultaneous modification.

You can use parallel Guava extensions for easier control of Future s, using, for example, Futures.allAsList() , which converts a List<Future<T>> to Future<List<T>> , so that you only have one get() to wait for all the answers.

+5
source
 for (i = 0; i <= numOfServiceCalls; i++) { new Thread(new Runnable() { switch(i) { case 1 : serviceOneCall(); break(); case 2 : serviceTwoCall(); break(); // Keep going with as many cases as you have. } }); } 
-2
source

Source: https://habr.com/ru/post/1434059/


All Articles