View Javadoc
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  
18  import java.util.concurrent.RecursiveTask;
19  
20  /**
21   * Codebeispiel zu RecursiveTask für die Summierung eines int-Arrays.
22   */
23  @SuppressWarnings("serial")
24  public final class SumTask extends RecursiveTask<Long> {
25  
26      private static final int THRESHOLD = 4;
27      private final int[] array;
28      private final int min;
29      private final int max;
30  
31      /**
32       * Erzeugt einen Array-Sumierer Task.
33       *
34       * @param array Interger-Array.
35       */
36      public SumTask(final int[] array) {
37          this(array, 0, array.length);
38      }
39  
40      private SumTask(final int[] array, final int min, final int max) {
41          this.array = array;
42          this.min = min;
43          this.max = max;
44      }
45  
46      @Override
47      protected Long compute() {
48          long sum = 0;
49          if ((max - min) <= THRESHOLD) {
50              for (int i = min; i < max; i++) {
51                  sum += array[i];
52              }
53          } else {
54              final int mid = min + (max - min) / 2;
55              final SumTask taskLeft = new SumTask(array, min, mid);
56              taskLeft.fork();
57              final SumTask taskRight = new SumTask(array, mid, max);
58              sum = taskRight.invoke() + taskLeft.join();
59          }
60          return sum;
61      }
62  }