Java 8: Parallel FOR loop Java 8: Parallel FOR loop java java

Java 8: Parallel FOR loop


Read up on streams, they're all the new rage.

Pay especially close attention to the bit about parallelism:

"Processing elements with an explicit for-loop is inherently serial. Streams facilitate parallel execution by reframing the computation as a pipeline of aggregate operations, rather than as imperative operations on each individual element. All streams operations can execute either in serial or in parallel."

So to recap, there are no parallel for-loops, they're inherently serial. Streams however can do the job. Take a look at the following code:

    Set<Server> servers = getServers();    Map<String, String> serverData = new ConcurrentHashMap<>();    servers.parallelStream().forEach((server) -> {        serverData.put(server.getIdentifier(), server.fetchData());    });


That would be using a Stream:

servers.parallelStream().forEach(server -> {    serverData.put(server.getIdentifier(), server.fetchData());});

I suspect a Collector can be used to greater effect here, since you use a concurrent collection.


More elegant or functional solution will be just using Collectors toMap or toConcurrentMap function, which avoid maintaining another stateful variable for ConcurrentHashMap, as following example:

final Set<Server> servers = getServers();Map<String, String> serverData = servers.parallelStream().collect(    toConcurrentMap(Server::getIdentifier, Server::fetchData));

Note: 1. Those functional interfaces (Server::getIdentifier or Server::fetchData) doesn't allow throw checked exception here, 2. To get the full benefits of parallel stream, the number of servers would be large and there is no I/O involved, purely data processing in those functions(getIdentifier, fetchData)

Please refer to Collectors javadoc at http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toConcurrentMap