【发布时间】:2015-08-25 19:42:38
【问题描述】:
在这里,我使用 Javaparallel 流来遍历 List 并以每个列表元素作为输入调用 REST 调用。我需要将 REST 调用的所有结果添加到我使用 ArrayList 的集合中。下面给出的代码工作正常,只是 ArrayList 的非线程安全性会导致不正确的结果,并且添加所需的同步会导致争用,从而破坏并行性的好处。
有人可以建议我在我的情况下使用并行流的正确方法吗?
public void myMethod() {
List<List<String>> partitions = getInputData();
final List<String> allResult = new ArrayList<String>();
partitions.parallelStream().forEach(serverList -> callRestAPI(serverList, allResult);
}
private void callRestAPI(List<String> serverList, List<String> allResult) {
List<String> result = //Do a REST call.
allResult.addAll(result);
}
【问题讨论】:
-
这个问题已经得到解答,但是我建议你不要使用并行流来并行执行多个 API 调用。有关解释,请参阅此问题和答案:stackoverflow.com/questions/34945324/…
标签: java multithreading concurrency parallel-processing java-8