Nali
Nali

Reputation: 157

Parallelizing a call in java

I have the following code:

List<ObjectA> allObjects = (List<ObjectA>) objArepository.findAll();

for (ObjectA objA : allObjects) {
        String location = objA.getUrl();

        Client client = utils.createClient();
        WebTarget webTarget = client.target(location).path("/testUrl/" + someString); 
        Invocation.Builder requestBuilder = webTarget.request();
        Response response;
        try {
            response = request.invoke();
            }
        }

instead of the for loop which sends those calls serially, I would like to send those calls all parallely, the problem is for that I didn't find any examples and I am missing an idea how to do that in java

Upvotes: 1

Views: 182

Answers (1)

Felix Wu
Felix Wu

Reputation: 46

Use ExecutorService.

The executorService.invokeAll can execute a list of tasks in parallel and wait them to complete.

ExecutorService executor = getExecutorService();
List<Request> requests = getRequests();
List<Callable> tasks = requests.stream()
    .map(r -> new Processor(r))
    .collect(Collectors.toList());

executor.invokeAll(tasks);

If you need asynchronous calls, use executorService.submit or executorService.execute

Update

According to the comment, I add a few more words about the code above.

getExecutorServices() returns a executorService created in other places, maybe a singleton, since the creation of an executorService is quite expensive.

getRequests() returns a list of requests, Request can be anything you want to process, such as ObjectA in the question.

executorService.invokeAll accepts a list of Callable, so you have to encapsulate your requests in callables. Processor is a callable to process Request.

Actually, I think the code is quite descriptive and an ordinary Java programmer can understand it.

Upvotes: 1

Related Questions