Search code examples
multithreadingparallel-processingjava.util.concurrent

Perform a task 'n' times in parallel


I am trying to figure out the easiest way to invoke a task 'x' times and all in parallel in java. The task has a string variable whose value should be unique for each invocation and it returns a string and int result.

I have been looking up resources in internet and now I am terribly confused.


Solution

  • In order to execute tasks in parallel, your first choice should be an ExecutorService. You get an instance of one like they say in the docs, that is

    ExecutorService service = Executors.newFixedThreadPool(poolSize);
    

    If your tasks must return a value, you should use the

    Future<T> submit(Callable<T> task);
    

    function. Make your tasks implement the Callable interface, returning the result you require. Submit your tasks to the service, then wait for the results through the Future objects. A rough sketch:

    public class MyTask implements Callable<StringInt> {
        public MyTask(String inputParameter) { ... }
        public StringInt call() { ... }
    }
    
    ...
    
    List<Future<StringInt>> results = new ArrayList<Future<StringInt>>();
    ExecutorService service = Executors.newFixedThreadPool(16);
    for (String inputParameter : inputParameters) {
        // Create tasks and start parallel execution
        results.add(service.submit(new MyTask(inputParameter)));
    }
    
    for (Future<StringInt> result : results) {
        // Wait for tasks to end, and get result
        StringInt resultValue = result.get();
        ...
    }