View Javadoc

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