Skip to content

Commit c322201

Browse files
committed
[update] update parallel examples in Java 8 module
1 parent 9c9b542 commit c322201

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

java8/README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
- CollectorHarness: 比较收集器的性能
4040

4141

42+
并行数据处理
4243

43-
44-
44+
- ParallelStreamsHarness: 测量流性能
45+
- ParallelStreams: 并行流计算 1~n 的和,分别使用指令式,串行迭代流,并行迭代流,基本类型流,有副作用的流
46+
- ForkJoinSumCalculator: 使用分支/合并框架执行并行求和
47+
- WordCount: Spliterator: splitable iterator

java8/src/main/java/com/brianway/learning/java8/streamapi/parallel/ParallelStreams.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
*/
1010
public class ParallelStreams {
1111

12+
/**
13+
* for 循环的迭代
14+
*/
1215
public static long iterativeSum(long n) {
1316
long result = 0;
1417
for (long i = 0; i <= n; i++) {
@@ -21,10 +24,20 @@ public static long sequentialSum(long n) {
2124
return Stream.iterate(1L, i -> i + 1).limit(n).reduce(Long::sum).get();
2225
}
2326

27+
/**
28+
* iterate 的问题:
29+
* - iterate 生成的是装箱的对象,必须拆成数字才能求和
30+
* - 很难把 iterate 分成多个独立块来并行执行
31+
*/
2432
public static long parallelSum(long n) {
2533
return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(Long::sum).get();
2634
}
2735

36+
/**
37+
* 使用 LongStream.rangeClosed
38+
* - 没有装箱拆箱
39+
* - 容易拆分为独立的小块
40+
*/
2841
public static long rangedSum(long n) {
2942
return LongStream.rangeClosed(1, n).reduce(Long::sum).getAsLong();
3043
}
@@ -39,6 +52,9 @@ public static long sideEffectSum(long n) {
3952
return accumulator.total;
4053
}
4154

55+
/**
56+
* 共享了可变状态,导致每次结果不一致
57+
*/
4258
public static long sideEffectParallelSum(long n) {
4359
Accumulator accumulator = new Accumulator();
4460
LongStream.rangeClosed(1, n).parallel().forEach(accumulator::add);

java8/src/main/java/com/brianway/learning/java8/streamapi/parallel/ParallelStreamsHarness.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import java.util.concurrent.ForkJoinPool;
44
import java.util.function.Function;
55

6+
/**
7+
* 测量流性能
8+
*/
69
public class ParallelStreamsHarness {
710

811
public static final ForkJoinPool FORK_JOIN_POOL = new ForkJoinPool();

0 commit comments

Comments
 (0)