【发布时间】:2019-09-11 10:38:39
【问题描述】:
我正在使用流 API reduce 来测试 String 的数组列表。
for (int i = 0; i < 100; i++)
{
Stream<String> s1 = Stream.of("aa", "ab", "c", "ad");
Predicate<String> predicate = t -> t.contains("a");
List<String> strings2 = new ArrayList<>();
s1.parallel().reduce(new ArrayList<String>(),
new BiFunction<ArrayList<String>, String, ArrayList<String>>()
{
@Override
public ArrayList<String> apply(ArrayList<String> strings, String s)
{
if (predicate.test(s))
{
strings.add(s);
}
return strings;
}
}, new BinaryOperator<ArrayList<String>>()
{
@Override
public ArrayList<String> apply(ArrayList<String> strings,
ArrayList<String> strings2)
{
return strings;
}
}).stream().forEach( //
e -> {
strings2.add(e);
});
if (strings2.contains(null))
{
System.out.println(strings2);
}
}
}
我浏览了几个博客,上面说可以在这种情况下使用 reduce,并且可以保证同步,但上面的情况看起来不是这样。 该测试在几个测试运行中为 TRUE,
strings2.contains(null)
所以我的问题是: 是我使用reduce的方式不正确,还是需要做一些额外的事情来确保sych?
【问题讨论】:
-
s1.parallel()创建并行流,如Parallelism tutorialAggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it中所述,累加器和组合器函数不应修改strings列表。使用串行流 (s1.reduce(...) 可能是保证“同步”的解决方案 -
无论你读过什么博客,都不要再读了。
List<String> strings2 = Stream.of("aa", "ab", "c", "ad") .parallel() .filter(t -> t.contains("a")) .collect(Collectors.toList());是这样做的正确方法。你正在做的事情,已经坏了并且非常复杂。 -
@Holger 首先,感谢您在这里完成的 cmets。我对这个问题的观点不是'最好在这里使用
filter或reduce,但我确实想学习如何以适当的方式使用reduce,换句话说,以线程安全的方式。我认为reduce函数是线程安全的,但是它在这里显示的内容证明我错了,所以我想知道这里是否有reduce的线程安全方式。 -
如果使用正确,
reduce是线程安全的。事实上,每个线程安全构造只有在正确使用时才是安全的。但是当一个博客说“reduce 可以在 this 的情况下使用”时,这是非常错误的。
标签: java java-stream reduce