我正在执行在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;
}
};