Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #30 Parallelize execution of 1000 independent tasks

Launch the concurrent execution of the procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
final ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for (int i = 1; i <= 1000; i++) {
  executor.submit(() -> f(i));
}
executor.shutdown();

For a large number of tasks, use a thread pool.
(dorun (pmap f (range 1 1001)))

New implementation...