So I am trying to understand about how ForkJoinPool works. I am trying to achieve better performance using this for a large array of about 2 million elements and then adding their reciprocal. I understand that ForkJoinPool.commpnPool().invoke(task); calls compute() which forks the task in two tasks if it is not smaller and then computes and then joins them. So far, we are using two cores.
But if I want to xecute this on multiple cores, how do I do that and achieve 4 times better performance than the usual single thread run? Below is my code for default ForkJoinPool():
@Override protected void compute() { // TODO if (endIndexExclusive - startIndexInclusive <= seq_count) { for (int i = startIndexInclusive; i < endIndexExclusive; i++) value += 1 / input[i]; } else { ReciprocalArraySumTask left = new ReciprocalArraySumTask(startIndexInclusive, (endIndexExclusive + startIndexInclusive) / 2, input); ReciprocalArraySumTask right = new ReciprocalArraySumTask((endIndexExclusive + startIndexInclusive) / 2, endIndexExclusive, input); left.fork(); right.compute(); left.join(); value = left.value + right.value; } } } protected static double parArraySum(final double[] input) { assert input.length % 2 == 0; double sum = 0; // Compute sum of reciprocals of array elements ReciprocalArraySumTask task = new ReciprocalArraySumTask(0, input.length, input); ForkJoinPool.commonPool().invoke(task); return task.getValue(); } //Here I am trying to achieve with 4 cores protected static double parManyTaskArraySum(final double[] input, final int numTasks) { double sum = 0; System.out.println("Total tasks = " + numTasks); System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", String.valueOf(numTasks)); // Compute sum of reciprocals of array elements int chunkSize = ReciprocalArraySum.getChunkSize(numTasks, input.length); System.out.println("Chunk size = " + chunkSize); ReciprocalArraySumTask task = new ReciprocalArraySumTask(0, input.length, input); ForkJoinPool pool = new ForkJoinPool(); // pool. ForkJoinPool.commonPool().invoke(task); return task.getValue(); }