Call a method for List in parallel?

Károly Neue :

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
}
bramdc :

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: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html#executing_streams_in_parallel

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?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4377&siteId=1