原本引用如下
Side-effects in behavioral parameters to stream operations are, in general,discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
所谓副作用,在我理解是;当我操作流的过程中,影响了流本身以外其他的状态/变量即谓之产生了副作用(影响流本身当然也是不允许的);
举例一段简单代码
下面的代码会打印出非预期的效果, 即 matched size并不是9900,并且每次都不同;
List<Integer> matched = new ArrayList<>();
List<Integer> elements = new ArrayList<>();
for(int i=0 ; i< 10000 ; i++) {
elements.add(i);
}
IntStream.range(0, 5).forEach(a -> {
matched.clear();
elements.parallelStream()
.forEach(e -> {
if(e >= 100) {
matched.add(e);
}
});
System.out.println(matched.size());
});
可以很明显的察觉到是因为并发性问题;如果我们试图用Collections.synchronizedList去封装一下需要处理的matched, 或者将paralleStream 修改为stream问题就可以解决;但是代价就是
- 不进行并行计算的优势;
- 为支持并行计算,必须使用支持并发的容器;造成的资源竞争损耗,和代码复杂度的提升可能得不尝失;
因为在操作流的过程中,Oracle官方的建议是尽量不要造成Side effect影响,而是要在Stream里产生一个新的结果; 改写如下:
IntStream.range(0, 5).forEach(a -> {
List<Integer> matched = elements.parallelStream().filter(b -> b >= 100).collect(Collectors.toList());
System.out.println(matched.size());
});
有时候,我们可能不得不去产生side affect(从书写简单,或者其他性能开销考虑);那么以下几点满足一点应该就是可行得;
- 放弃并发计算(即不要使用parallelStream)这样就退回了普通得遍历迭代;
- 确保被影响的对象是经过线程安全的;
- 自己考虑在parallelStream中进行的操作,本身就是线程安全的(不在意一并发执行);