Say I have a task like:
for(Object object: objects) {
Result result = compute(object);
list.add(result);
}
What is the easiest way to parallelize each compute() (assuming they are already parallelizable)?
I do not need an answer that matches strictly the code above, just a general answer. But if you need more info: my tasks are IO bound and this is for a Spring Web application and the tasks are going to be executed in a HTTP request.
I would recommend taking a look at ExecutorService.
In particular, something like this:
Note that using
newCachedThreadPoolcould be bad ifobjectsis a big list. A cached thread pool could create a thread per task! You may want to usenewFixedThreadPool(n)where n is something reasonable (like the number of cores you have, assumingcompute()is CPU bound).Here’s full code that actually runs: