Call a method for List in parallel?

I must iterate over an list and call for every object a method, but in parallel. After the loop, there other statements, which must wait for the parallel method invocations. How can I do that in JAVA?

public void a(List<Object> list) {
    for(Object o : list) {
        asynchMethod(o); // this n method call must run in the same time

    // wait for all asynchMethod result
     * ...other statements

private void asynchMethod(Object o) {
    // some code

I see that you are using java 8, you can then use the parallelStream approach:

public void a(List<Object> list) {
    list.parallelStream().forEach(s -> asyncMethod(o));

which must wait for the parallel method invocations

The foreach is a terminal operation aka it will wait to be finished until moving forward to the next code line: Java parallel stream: how to wait for threads for a parallel stream to finish?

If you want some more information about parallelStream:

If you want to know how many threads parallelstream uses: How many threads are spawned in parallelStream in Java 8?

Watch out with using threads and pararellStream, they come with their own heap of problems. Before using them you should always carefully examine the situation and see if they are worth the trouble they can possible bring: Should I always use a parallel stream when possible?

10 Examples of forEach() method in Java 8, Once the list is filtered than forEach() method will print all elements starting with You can even do filtering and transformation and * can run the loop in parallel. In the next article, I am going to discuss the Parallel ForEach Method in C# with some examples. Here, In this article, I try to explain the Parallel For in C# with some examples. I hope you understood the need and use of Parallel For method in C#. Please have a look at our LINQ Tutorials. LINQ Tutorial For Beginners and Professionals

One fool proof way (out of many) to execute any method in parallel is to start a thread pool and then assign tasks to it and wait for the tasks to finish.

public static ThreadPoolExecutor getExecutorService(int poolSize, int maxPoolSize{
  int threadPoolshutDownTime = 10L;
  ThreadPoolExecutor executorService= new ThreadPoolExecutor(poolSize, maxPoolSize, threadPoolshutDownTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
  executorService.allowCoreThreadTimeOut(true); // allows the threadpool to shutdown if no task is assigned
  return executorService;

Now call this inside your method like the following :

public void a(List<Object> list) throws InterruptedException, ExecutionException  {

  List<Callable<Boolean>> callables = new ArrayList<>(list.size());
  list.forEach(object ->callables.add(() -> return asynchMethod(object)));

  for (Future<Boolean> booleanFuture : this.getExecutorService(1,4).invokeAll(callables)) {
            booleanFuture.get(); //this will wait for the callables to be done!

Also modify your aysncMethod as the following :

private boolean asynchMethod(Object o) {
    return o.doMagic(); //doMagic returns a boolean when completed

How to call a method simultaneously for each element in a list using , parallel() method but I was unable to configure it correctly, what I want is to avoid calling method one by one and parallelly call and run the� The code and parameters in this example closely resemble the corresponding For method. For more information, see How to: Write a Parallel.For Loop with Thread-Local Variables. To use a partition-local variable in a ForEach loop, you must call one of the method overloads that

Use CompletableFuture.

  .map(i -> CompletableFuture.submit(o -> asyncMethod(I))

Parallelism (The Java™ Tutorials > Collections > Aggregate , To create a parallel stream, invoke the operation Collection.parallelStream . Sex, List<Person>> byGender = roster .stream() .collect( Collectors. To determine the characteristics of a collector, invoke the Collector.characteristics method. How to call multiple methods in parallel with different return types. In a multi-thread programming applications development, Java concurrency API provides an ExecutorService interface that represents an asynchronous execution mechanism which is capable of executing multiple tasks in the background.

18. Parallel Streams, To create a parallel stream from a Collection use the parallelStream() method: Printing a list of elements with a sequential stream will output the expected result: or worse, the entire operation may run in parallel, like the following example:. Parallel LINQ enables you to optimize your queries by splitting them into parts so as to execute these parts in parallel and hence boost the query performance. In this article we would discuss

Java 8 Stream (with Examples), Stream operations can either be executed sequentially or parallel. when In the given example, we are creating a stream from the List. Intermediate operations return the stream itself so you can chain multiple methods calls in a row. The Parallel.For method may use more tasks than threads over the lifetime of its execution, as existing tasks complete and are replaced by new tasks. This gives the underlying TaskScheduler object the chance to add, change, or remove threads that service the loop.

Parallel.Invoke Method (System.Threading.Tasks), Executes each of the provided actions, possibly in parallel. In this article. Definition; Overloads; Invoke(Action[]); Invoke(ParallelOptions, Action[]); Applies to� This Parallel Foreach method takes our list of strings(the websites’ URL’s) as the first parameter and as second parameter it takes an Action. So we use a lambda expression to call the “GetStr” method for each site in our list. 5-The results from the “GetStr” method are added to the list that the method will return.

  • Are you using java 8?
  • @BeUndead Yes, I am using java 8
  • Please look at Java 8 - Call methods async in parallel and combine their results
  • Does calling asynchMethod(obj) modify obj to know that the result has completed? How do you wait? If the YourObject.class contains something like isCompleted()
  • Instead of returning void from asynchMethod , return a Future Object. You can then join and wait for Future
  • the methods doesn't run in parallell, in sequence on the same thread
  • @KárolyNeue: the Stream::parallelStream method will use the invoking Thread. If there are lots of items in the List, it will also use other Threads (from the fork-join-pool). It may well end up running them all sequentially on the invoking Thread if it believes that context switching to other Threads will not save time for the specific List being streamed.
  • @KárolyNeue have a looks at this SO question:…
  • thanks, that works. But the asyncMethod and the a method are in the same EJB bean, and when I call the asynchMethod, than get a NullPointerException for the entityManager. Can you help me, how to resolve it?
  • @KárolyNeue I will be glad to help, but need more information. Maybe it's best to create another question on StackOverflow if you can't find a solution to your problem.