我使用ForkJoinPool并行执行任务。当我查看我的程序的注销时,似乎ForkJoinPool创建了大量的工作人员来执行我的任务(有类似于05 Apr 2016 11:39:18,678 [ForkJoinPool-2-worker-2493] <message>的日志条目)。
对于创建的每个任务是否有一个工作人员,然后根据我在ForkJoinPool中配置的并行性的数量来执行,还是我做错了什么?我就是这样做的:
public class MyClass {
private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();
public MyClass() {
int maxThreads = NUM_CORES * 2;
this.forkJoinPool = new ForkJoinPool(maxThreads);
}
public void doStuff() {
final int[] toIndex = {0};
forkJoinPool.submit(() -> {
List<ForkJoinTask> tasks = new ArrayList<>();
while (toIndex[0] < objects.size()) {
toIndex[0] += 20;
List<Object> bucket = objects.subList(toIndex[0] - 20, toIndex[0]);
ForkJoinTask task = new UpdateAction(bucket);
tasks.add(task);
task.fork();
}
tasks.forEach(ForkJoinTask::join);
}).join();
}
private class UpdateAction extends RecursiveAction {
private List<Object> bucket;
private UpdateAction(List<Object> bucket) {
this.bucket = bucket;
}
@Override
protected void compute() {
// do some calculation
}
}
}发布于 2016-04-05 10:46:33
任务名称末尾的数字与池使用的实际线程数无关。查看一下registerWorker类的ForkJoinPool方法。看起来是这样的:
final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
UncaughtExceptionHandler handler;
wt.setDaemon(true); // configure thread
if ((handler = ueh) != null)
wt.setUncaughtExceptionHandler(handler);
WorkQueue w = new WorkQueue(this, wt);
int i = 0; // assign a pool index
int mode = config & MODE_MASK;
int rs = lockRunState();
...
// some manipulations with i counter
...
wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
return w;
}workerNamePrefix初始化为
"ForkJoinPool-" + nextPoolId() + "-worker-" 如果要度量池使用的线程的实际数量,最好记录getPoolSize()返回的内容。
https://stackoverflow.com/questions/36422654
复制相似问题