I have 8-cores CPU and I'm going parallelise one recursive task into a few subtask. The thing is I wouldn't like that the amount of threads would be more than the amount of the CPU-cores. So, I have a class
public class ValueSumCounter extends RecursiveTask<Long>{
byte[] bytesToProcess;
public ValueSumCounter(byte[] b) {
this.bytesToProcess = b;
}
@Override
protected Long compute() {
List<ValueSumCounter> tasksToCompute;
//Obtaining list of tasks (more than 100)
}
for(ValueSumCounter task : tasksToCompute) {
task.join();
}
}
and now, I wannta create the ForkJoinPool as follows:
public static void main(String[] args) {
byte[] bytes;
//Obtaining bytes of an image and set their to bytes
new ForkJoinPool().invoke(new ValueSumCounter(bytes));
}
And I don't know how much threads will be created during this invocation. How can I bound the amount of threads explicitly less than the number of cores (8 in my case)?
You can create the ForkJoinPool with an int as Constructor parameter ( http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#ForkJoinPool-int- ), so you can controll how many worker threads the ForkJoinPool will use. In your case you want to have 8, because you have 8 cores and can call it like:
new ForkJoinPool(Runtime.getRuntime().availableProcessors());
Edit: As "isnot2bad" noted you actually don't need to specify the number of worker threads, because the no-argument constructor already uses your desired number: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#ForkJoinPool--
I overlooked this, thanks for the addition.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.