fork download
  1. import java.util.List;
  2. import java.util.concurrent.ForkJoinPool;
  3. import java.util.concurrent.ForkJoinTask;
  4. import java.util.concurrent.RecursiveTask;
  5.  
  6. class Ideone
  7. {
  8. public static void main(String[] args) {
  9. // 2 active workers
  10. ForkJoinPool pool = new ForkJoinPool(2);
  11.  
  12. // whatever many elements in the list
  13. List<Integer> original = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
  14.  
  15. // main task will split up the list into sub threads
  16. int result = pool.invoke(new ParallelSum(original, 0, original.size()));
  17. System.out.println("Expected Result: " + original.stream().mapToInt(Integer::intValue).sum());
  18. System.out.println("Actual Result: " + result);
  19. }
  20.  
  21. static class ParallelSum extends RecursiveTask<Integer> {
  22. private static final int THRESHOLD = 4;
  23. private final List<Integer> ints;
  24. private final int offset, batchSize;
  25.  
  26. ParallelSum(List<Integer> ints, int offset, int batchSize) {
  27. this.ints = ints;
  28. this.offset = offset;
  29. this.batchSize = batchSize;
  30. }
  31.  
  32. @Override
  33. protected Integer compute() {
  34. if (batchSize <= THRESHOLD) {
  35. // process this batch
  36. int sum = 0;
  37. for (int i = 0; i < batchSize; i++) {
  38. sum += ints.get(offset + i);
  39. }
  40. System.out.println(Thread.currentThread().getName() + " processed batch of size: " + batchSize + " from offset: " + offset + " and got sum: " + sum);
  41. return sum;
  42. } else {
  43. // divide and conquer
  44. int newLength = batchSize / 2;
  45. var tasks = List.of(
  46. new ParallelSum(ints, offset, newLength),
  47. // the `bitwise and` helps us to divide odd number of tasks
  48. new ParallelSum(ints, offset + newLength, newLength + (batchSize & 1))
  49. );
  50. return ForkJoinTask.invokeAll(tasks)
  51. .stream()
  52. .mapToInt(ForkJoinTask::join)
  53. .sum();
  54. }
  55. }
  56. }
  57. }
Success #stdin #stdout 0.24s 62032KB
stdin
Standard input is empty
stdout
ForkJoinPool-1-worker-1 processed batch of size: 2 from offset: 9 and got sum: 21
ForkJoinPool-1-worker-1 processed batch of size: 3 from offset: 11 and got sum: 39
ForkJoinPool-1-worker-3 processed batch of size: 4 from offset: 0 and got sum: 10
ForkJoinPool-1-worker-3 processed batch of size: 2 from offset: 4 and got sum: 11
ForkJoinPool-1-worker-3 processed batch of size: 3 from offset: 6 and got sum: 24
ForkJoinPool-1-worker-3 processed batch of size: 2 from offset: 14 and got sum: 31
ForkJoinPool-1-worker-1 processed batch of size: 3 from offset: 16 and got sum: 54
Expected Result: 190
Actual Result:   190