CountedCompleter使用示例:
- CountedCompleter是Fork/join框架中ForkJoinTask的又一个子类(其它两个为RecursiveAction、RecursiveTask)。
- CountedCompleter会记住目前还在进行中的任务数,并且可以通知onCompletion这个方法。
- 进行中的任务数可以通过调用CountedCompleter#addToPendingCount()来增加,我们在fork一个task的时候务必调用这个方法,表明进行中的任务+1。
- 既然有加,那么一定就有减。在实现compute方法中,需要在函数返回return前调用CountedCompleter#tryComplete()方法,tryComplete方法是在CountedCmpleter中被定义的final方法,它会检查进行中的任务数是否为0,如果为0,则调用子类实现的onCompletion方法,如果不为0,则把进行中的任务数减1。
- CountedCompleter可以返回,也可以不返回一个值。如果需要返回,那么一定要重载getRawResult方法
package forkjoin;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountedCompleter;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicReference;
public class CountedCompleterExample {
public static void main (String[] args) {
List<BigInteger> list = new ArrayList<>();
for (int i = 3; i < 20; i++) {
list.add(new BigInteger(Integer.toString(i)));
}
BigInteger sum = ForkJoinPool.commonPool().
invoke(new FactorialTask(null,
new AtomicReference<>(new BigInteger("0")),
list));
System.out.println("Sum of the factorials = " + sum);
}
private static class FactorialTask extends CountedCompleter<BigInteger> {
private static int SEQUENTIAL_THRESHOLD = 5;
private List<BigInteger> integerList;
private AtomicReference<BigInteger> result;
private FactorialTask (CountedCompleter<BigInteger> parent,
AtomicReference<BigInteger> result,
List<BigInteger> integerList) {
super(parent);
this.integerList = integerList;
this.result = result;
}
@Override
public BigInteger getRawResult () {
return result.get();
}
@Override
public void compute () {
//this example creates all sub-tasks in this while loop
while (integerList.size() > SEQUENTIAL_THRESHOLD) {
//end of the list containing SEQUENTIAL_THRESHOLD items.
List<BigInteger> newTaskList = integerList.subList(integerList.size() -
SEQUENTIAL_THRESHOLD, integerList.size());
//remaining list
integerList = integerList.subList(0, integerList.size() -
SEQUENTIAL_THRESHOLD);
addToPendingCount(1);
FactorialTask task = new FactorialTask(this, result, newTaskList);
task.fork();
}
//find sum of factorials of the remaining this.integerList
sumFactorials();
propagateCompletion();
}
private void addFactorialToResult (BigInteger factorial) {
result.getAndAccumulate(factorial, (b1, b2) -> b1.add(b2));
}
private void sumFactorials () {
for (BigInteger i : integerList) {
addFactorialToResult(CalcUtil.calculateFactorial(i));
}
}
}
}
Referencce: https://www.logicbig.com/how-to/code-snippets/jcode-java-concurrency-countedcompleter.html
本文介绍CountedCompleter在Fork/join框架中的使用,通过示例代码讲解如何利用CountedCompleter进行任务分解与合并,实现高效并行计算。

被折叠的 条评论
为什么被折叠?



