View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.surefire.api.runorder;
20  
21  import java.util.ArrayList;
22  import java.util.List;
23  
24  /**
25   * @author Kristian Rosenvold
26   */
27  public class ThreadedExecutionScheduler {
28      private final int numThreads;
29  
30      private final int runTime[];
31  
32      private final List<Class<?>>[] lists;
33  
34      @SuppressWarnings("unchecked")
35      public ThreadedExecutionScheduler(int numThreads) {
36          this.numThreads = numThreads;
37          runTime = new int[numThreads];
38          lists = new List[numThreads];
39          for (int i = 0; i < numThreads; i++) {
40              lists[i] = new ArrayList<>();
41          }
42      }
43  
44      public void addTest(PrioritizedTest prioritizedTest) {
45          final int leastBusySlot = findLeastBusySlot();
46          runTime[leastBusySlot] += prioritizedTest.getTotalRuntime();
47          //noinspection unchecked
48          lists[leastBusySlot].add(prioritizedTest.getClazz());
49      }
50  
51      public List<Class<?>> getResult() {
52          List<Class<?>> result = new ArrayList<>();
53          int index = 0;
54          boolean added;
55          do {
56              added = false;
57              for (int i = 0; i < numThreads; i++) {
58                  if (lists[i].size() > index) {
59                      result.add(lists[i].get(index));
60                      added = true;
61                  }
62              }
63              index++;
64          } while (added);
65          return result;
66      }
67  
68      private int findLeastBusySlot() {
69          int leastBusy = 0;
70          int minRuntime = runTime[0];
71          for (int i = 1; i < numThreads; i++) {
72              if (runTime[i] < minRuntime) {
73                  leastBusy = i;
74                  minRuntime = runTime[i];
75              }
76          }
77          return leastBusy;
78      }
79  }