SumTask.java

  1. /*
  2.  * Copyright 2024 Hochschule Luzern Informatik.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package ch.hslu.exercises.sw11.ex1.n41.array.sum;

  17. import java.util.concurrent.RecursiveTask;

  18. /**
  19.  * Codebeispiel zu RecursiveTask für die Summierung eines int-Arrays.
  20.  */
  21. @SuppressWarnings("serial")
  22. public final class SumTask extends RecursiveTask<Long> {

  23.     private static final int THRESHOLD = 4;
  24.     private final int[] array;
  25.     private final int min;
  26.     private final int max;

  27.     /**
  28.      * Erzeugt einen Array-Sumierer Task.
  29.      *
  30.      * @param array Interger-Array.
  31.      */
  32.     public SumTask(final int[] array) {
  33.         this(array, 0, array.length);
  34.     }

  35.     private SumTask(final int[] array, final int min, final int max) {
  36.         this.array = array;
  37.         this.min = min;
  38.         this.max = max;
  39.     }

  40.     @Override
  41.     protected Long compute() {
  42.         long sum = 0;
  43.         if ((max - min) <= THRESHOLD) {
  44.             for (int i = min; i < max; i++) {
  45.                 sum += array[i];
  46.             }
  47.         } else {
  48.             final int mid = min + (max - min) / 2;
  49.             final SumTask taskLeft = new SumTask(array, min, mid);
  50.             taskLeft.fork();
  51.             final SumTask taskRight = new SumTask(array, mid, max);
  52.             sum = taskRight.invoke() + taskLeft.join();
  53.         }
  54.         return sum;
  55.     }
  56. }