java – 如何配置单线程ForkJoinPool?

是否可以将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;
    }
};

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...