加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何配置单线程ForkJoinPool?

发布时间:2020-12-14 05:53:59 所属栏目:Java 来源:网络整理
导读:是否可以将ForkJoinPool配置为使用1个执行线程? 我正在执行在ForkJoinPool中调用Random的代码.每次运行时,我都会遇到不同的运行时行为,因此很难调查回归. 我希望代码库提供“调试”和“发布”模式. “debug”模式将使用固定种子配置Random,并使用单个执行线
是否可以将ForkJoinPool配置为使用1个执行线程?

我正在执行在ForkJoinPool中调用Random的代码.每次运行时,我都会遇到不同的运行时行为,因此很难调查回归.

我希望代码库提供“调试”和“发布”模式. “debug”模式将使用固定种子配置Random,并使用单个执行线程配置ForkJoinPool. “release”模式将使用系统提供的Random种子并使用默认数量的ForkJoinPool线程.

我尝试使用1的并行性配置ForkJoinPool,但它使用2个线程(主线程和第二个工作线程).有任何想法吗?

解决方法

所以,事实证明我错了.

将并行度设置为1的ForkJoinPool配置时,只有一个线程执行任务. ForkJoin.get()上阻止了主线程.它实际上并不执行任何任务.

也就是说,事实证明提供确定性行为真的很棘手.以下是我必须纠正的一些问题:

>如果工作线程空闲得足够长,ForkJoinPool正在使用不同的工作线程(具有不同的名称)执行任务.例如,如果主线程在调试断点上挂起,则工作线程将变为空闲并关闭.当我恢复执行时,ForkJoinThread将启动一个具有不同名称的新工作线程.为了解决这个问题,我不得不使用provide a custom ForkJoinWorkerThreadFactory implementation that returns null if the ForkJoinPool already has a live worker(这可以防止池创建多个worker).即使工作线程关闭并再次返回,我也确保我的代码返回相同的Random实例.
>具有非确定性迭代顺序的集合(例如HashMap或HashSet)导致元素在每次运行时以不同的顺序获取随机数.我通过使用LinkedHashMap和LinkedHashSet纠正了这个问题.
>具有非确定性hashCode()实现的对象,例如Enum.hashCode().我忘了这引起了什么问题但我通过自己计算hashCode()而不是依赖内置方法来纠正它.

这是ForkJoinWorkerThreadFactory的示例实现:

class MyForkJoinWorkerThread extends ForkJoinWorkerThread
{
    MyForkJoinWorkerThread(ForkJoinPool pool)
    {
        super(pool);
        // Change thread name after ForkJoinPool.registerWorker() does the same
        setName("DETERMINISTIC_WORKER");
    }
}

ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory()
{
    private WeakReference<Thread> currentWorker = new WeakReference<>(null);

    @Override
    public synchronized ForkJoinWorkerThread newThread(ForkJoinPool pool)
    {
        // If the pool already has a live thread,wait for it to shut down.
        Thread thread = currentWorker.get();
        if (thread != null && thread.isAlive())
        {
            try
            {
                thread.join();
            }
            catch (InterruptedException e)
            {
                log.error("",e);
            }
        }
        ForkJoinWorkerThread result = new MyForkJoinWorkerThread(pool);
        currentWorker = new WeakReference<>(result);
        return result;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读