Java8InAction学习笔记(四) - 18965050/Java8InAction GitHub Wiki

Parallel Stream

  • Stream.parallel()用于线程并行计算
  • Stream.sequential()用于串行计算

线程池线程数大小默认为可用的CPU数(Runtime.getRuntime().availableProcessors()), 可通过类似

System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "12");

这种方式修改.

使用parallel这种方式要注意:

  1. 并行的并非比串行的性能好. 存在线程切换的开销, unbox转换等
  2. 并行的操作应该是无状态的

集合Stream来源对Parallel友好程度: Stream souce对parallel的友好程度

Fork/Join框架

Fork/Join框架是Java7中引入的. 其逻辑为:

if (task is small enough or no longer divisible) {
	compute task sequentially
} else {
	split task in two subtasks
	call this method recursively possibly further splitting each subtask
	wait for the completion of all subtasks
	combine the results of each subtask
}

Spliterator

Spliterator全称为"splitable iterator", 作为parallel的chunk分割器.

public interface Spliterator<T> {
	boolean tryAdvance(Consumer<? super T> action);
	Spliterator<T> trySplit();
	long estimateSize();
	int characteristics();
}

Spliterator调用trySplit()方法, 如果有Spliterator对象返回, 则可以再分隔;如果返回null, 则不能在进行分割了. Spliterator.trySplit

characteristics()方法返回结果含义: Spliterator.characteristics

⚠️ **GitHub.com Fallback** ⚠️