What's the best way to parallelize a REST call? What's the best way to parallelize a REST call? multithreading multithreading

What's the best way to parallelize a REST call?


All you're looking for is to run your calls asynchronously. You can use CompletableFutures to submit the task, and then wait for them to complete:

list.stream() //you don't really need a parallel stream    .map(CompletableFuture::runAsync)    .collect(Collectors.toList()) //make sure all tasks are submitted    .stream()    .forEach(CompletableFuture::join);

This will submit all tasks (to run asynchronously), and then wait for each of them to finish running. When that happens, the method will return.

You may need to control the thread pool for your async tasks. This is an example using a 10-thread pool:

ExecutorService es = Executors.newFixedThreadPool(10);list.stream()    .map(r -> CompletableFuture.runAsync(r, es))     ...