1. parallelStream parallel stream
1.1 The difference between serial and parallel
2.1 Is parallelStream necessarily faster than Stream serial?
2.2 Can all be used in parallel?
1. parallelStream parallel stream
-
Multi-threaded concurrent processing, fast
-
The fork/join framework provides concurrent execution capabilities
-
The underlying principle: the thread pool (ForkjoinPool) maintains a thread queue and splits the parent task into subtasks
1.1 The difference between serial and parallel
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
System.out.println(">> 【串行 stream()】单线程");
list.stream().forEach(System.out::println);
System.out.println(">> 【并行 parallelStream()】多线程");
list.parallelStream().forEach(System.out::println);
}
> Execution results
2. Problems
2.1 Is parallelStream necessarily faster than Stream serial?
-
Error, if the amount of data is small, serialization may be faster, and ForkJoin will consume performance .
-
Parallel is faster than serial in most cases
2.2 Can all be used in parallel?
-
No, there will be thread safety issues in some cases . External variables used in parallelStream, such as collections, must use thread-safe collections, otherwise multi-thread safety issues will arise.
for (int i = 0; i < 10; i++) {
List list1 = new ArrayList();
IntStream.range(0,100).parallel().forEach(list1::add);
System.out.println(list1.size());
}
> Report error
3. Actual combat
- Insert 100 random [0,100] ints into the list, repeat 10 times
for (int i = 0; i < 10; i++) {
List list1 = new CopyOnWriteArrayList();
IntStream.range(0,100).parallel().forEach(list1::add);
System.out.println(list1.size());
}
> Execution results
4. Summary
General list.size()
-
Dozens: Using Stream
-
Hundreds or more: parallelStream