Fork does not (necessarily) create new threads. In my benchmark, it only creates 1 thread per available core + 1 extra thread. Attaching benchmark; call from main() as Factorizer.factorize(71236789143834319L)
, say.
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class Factorizer extends RecursiveTask<Long> {
static ForkJoinPool fjPool = new ForkJoinPool();
static final int sequentialThreshold = 10000;
private long number, low, high;
Factorizer(long number, long low, long high) {
this.number = number; this.low = low; this.high = high;
}
private long factorize() {
if ((number % 2) == 0) {
return 2;
}
// ensures i is odd (we already know number is not even)
long i = ((low % 2) == 0) ? low + 1: low;
for (/**/; i < high; i+=2) {
if ((number % i) == 0) {
return i;
}
}
return number;
}
@Override
protected Long compute() {
// ugly debug statement counts active threads
System.err.println(Thread.enumerate(
new Thread[Thread.activeCount()*2]));
if (high - low <= sequentialThreshold) {
return factorize();
} else {
long mid = low + (high - low) / 2;
Factorizer left = new Factorizer(number, low, mid);
Factorizer right = new Factorizer(number, mid, high);
left.fork();
return Math.min(right.compute(), left.join());
}
}
static long factorize(long num) {
return fjPool.invoke(new Factorizer(num, 2, (long)Math.sqrt(num+1)));
}
}
Note - this was only a test. Do not use this code to seriously try to factor anything big.