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