CountedCompleter使用示例一

本文介绍CountedCompleter在Fork/join框架中的使用,通过示例代码讲解如何利用CountedCompleter进行任务分解与合并,实现高效并行计算。

CountedCompleter使用示例:

  1. CountedCompleter是Fork/join框架中ForkJoinTask的又一个子类(其它两个为RecursiveAction、RecursiveTask)。
  2. CountedCompleter会记住目前还在进行中的任务数,并且可以通知onCompletion这个方法。
  3. 进行中的任务数可以通过调用CountedCompleter#addToPendingCount()来增加,我们在fork一个task的时候务必调用这个方法,表明进行中的任务+1。
  4. 既然有加,那么一定就有减。在实现compute方法中,需要在函数返回return前调用CountedCompleter#tryComplete()方法,tryComplete方法是在CountedCmpleter中被定义的final方法,它会检查进行中的任务数是否为0,如果为0,则调用子类实现的onCompletion方法,如果不为0,则把进行中的任务数减1。
  5. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值