1

考虑50,000个对象的集合。 每个对象通过其doWork()方法每次迭代产生10次双打。什么是最有效的并行实施方式?

有一个连续的while循环遍历50,000个对象中的每一个,并调用doWork()。 之后,创建的10个双打中的每一个都必须通过调用每个对象的process()来处理。

while循环内的最后一步必须对每次迭代中产生的双精度进行求和,然后记录输出。

设计是否取决于完成doWork()和process()所花费的相对时间?

什么是实现这种算法的最快和最有效的CPU方法?

我想利用多内核将有很大的帮助......

我应该使用的ExecutorService或ForkJoin?

我应该如何分配任务?

List<A> listA = new ArrayList<>(); 
populateWith50k(listA); // has 50k objects after this line 
List<Double> listB = new ArrayList<>(); 

while(true){ 

    // causes a side affect, hence a change of state that the remaining code 
    // depends on, hence I don't think we can use java streams... 
    changeState(); 

    // the below depends on the system state setup above 
    for (int i=0;i<listA.size();i++){ 
     A a = listA.get(i); 
     a.doWork(); 
     populateUsingA(a); // populates listB, each A creates 10 doubles 
     for (int j=0;j<listB.size();j++){ 
      B b = listB.get(j); 
      b.process(); 
     } 
     sumAndThenLogValuesInListB(a); 
     listB.clear(); 
    } 
} 

回答

2

您应该使用并行流。

listA.parallelStream().flatMapToDouble(A::doWork).sum() 

会给你一个通过while循环的总和。您需要更改doWork以立即输出十个双打,或者引入另一个方法来完成它,或者编写一个更复杂的lambda体来完成它(为了便于阅读,我不建议这么做)。

+0

changeState()方法中有一个副作用,所以我不确定这会起作用,由于复杂性我不能重构更多的功能代码样式,我简化了示例以使其更容易了解。对不起,我没有强调依赖于在while循环的每个循环中导致依赖状态改变的副作用。 – newlogic

相关问题