RecursiveAction Splits With Threshold
Split a ForkJoinTask at a sequential threshold with invokeAll so the work-stealing pool stops forking once segments are small enough.
Code
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ParallelFill {
static final int THRESHOLD = 4;
static final long[] data = new long[16];
// 就地填充一段 [lo, hi):小于阈值顺序做,否则二分后并行
static class FillTask extends RecursiveAction {
final int lo;
final int hi;
FillTask(int lo, int hi) {
this.lo = lo;
this.hi = hi;
}
@Override
protected void compute() {
if (hi - lo <= THRESHOLD) {
for (int i = lo; i < hi; i++) {
data[i] = i * i;
}
return;
}
int mid = (lo + hi) >>> 1;
// invokeAll fork 左右两个子任务并在当前线程 join,顺序无关
invokeAll(new FillTask(lo, mid), new FillTask(mid, hi));
}
}
public static void main(String[] args) {
// commonPool 是 JVM 全局共享池:AutoCloseable.close() 对它没有效果
// 也不等待(JDK 19+ 文档原文 "this method has no effect on execution,
// and does not wait"),公共池不能也不需要关闭——任务直接提交,
// 生命周期由 JVM 管理
ForkJoinPool.commonPool().invoke(new FillTask(0, data.length));
System.out.println("filled " + data.length + " slots");
System.out.println("data[3]=" + data[3] + " data[9]=" + data[9]);
}
}How the snippet works
The snippet is organized around the classes ParallelFill and FillTask and the functions compute and main.
for (int i = lo; i < hi; i++) is the loop that carries the per-item work.
What to watch for
- The imports (if any) point only at standard-library modules.
Applying it
Entry signature: protected void compute()
The run emits 2 labeled sections — filled, data[3]= — one per step.
Statements that matter
ForkJoinPool.commonPool().invoke(new FillTask(0, data.length));
invokeAll(new FillTask(lo, mid), new FillTask(mid, hi));
static final long[] data = new long[16];
Interactive Tools for This Topic
FAQ
- What does RecursiveAction Splits With Threshold print when run?
- Run it as a complete program — the output lines carry labels such as `filled`, `data[3]=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.