Zee*_*han 6 java parallel-processing concurrency multithreading java-8
在这里,我使用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);
}
您可以使用map而不是forEach- 这将保证线程安全(从功能编程的角度来看更清洁):
List<String> allResult = partitions.parallelStream()
          .map(this::callRestAPI)
          .flatMap(List::stream) //flattens the lists
          .collect(toList());
你的callRestAPI:
private List<String> callRestAPI(List<String> serverList) {
    List<String> result = //Do a REST call.
    return result;
}
| 归档时间: | 
 | 
| 查看次数: | 2481 次 | 
| 最近记录: |