简体   繁体   中英

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

I'm working on some java code, which processes multiple REST calls

call1()
call2()
call3()
...

I want to parallelize these calls, but perform my main code synchronously. I made a POC with lamba and a parallel stream:

List<Runnable> list = new ArrayList();
list.add(() -> {call1()});
list.add(() -> {call2()});
list.add(() -> {call3()});
list.add(...);

list.parallelStream()
            .forEach(Runnable::run);

Do you have another solution? I also checked to use async calls from Jersey client instead, but this would need more code changes.

All you're looking for is to run your calls asynchronously. You can use CompletableFuture s 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))
     ...

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