Streams and parallel streams

the difference

Isn't it parallel? Pay attention to the order.

This time, it is not the measurement of the processing order, but the measurement of the performance.

measurement

measurement.java


package test1;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Test3 {
	
	public static void main(String[] args) {
		Long start1 = System.nanoTime();
		normal();
		Long end1 = System.nanoTime();
		System.out.println("stream\r\n" + (end1 - start1) + "ns\r\n");
		Long start2 = System.nanoTime();
		parallel();
		Long end2 = System.nanoTime();
		System.out.println("parallelStream\r\n" + (end2 - start2) + "ns");
	}
	
	private static void normal() {
		generate().stream().filter(filter).map(v -> v + 1).forEachOrdered(qwe);
	}
	
	private static void parallel() {
		generate().parallelStream().filter(filter).map(v -> v + 1).forEachOrdered(qwe);
	}
	
	private static List<String> generate() {
		return IntStream.range(0, 9999).boxed().map(String::valueOf).collect(Collectors.toList());
	}
	
	private static final Predicate<String> filter = v -> v.length() == 3;
	private static final Consumer<String> qwe = v -> {};
}

result

stream
13381900ns

parallelStream
8380600ns

It's quite different

However ...

Because it is multi-threaded It is no longer thread-safe.

If you do something bad, you will get null or InterruptedException. Let's control synchronization firmly

Recommended Posts

Streams and parallel streams
Item 48: Use caution when making streams parallel
Parallel and parallel processing in various languages (Java edition)
Effective Java 3rd Edition Chapter 7 Lambda and Streams
Item 80: Prefer executors, tasks, and streams to threads