Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/java/test/org/openqa/selenium/ParallelTestRunner.java
1865 views
1
// Licensed to the Software Freedom Conservancy (SFC) under one
2
// or more contributor license agreements. See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership. The SFC licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License. You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied. See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
package org.openqa.selenium;
19
20
import java.util.ArrayList;
21
import java.util.List;
22
23
/** Utility class for concurrency tests. */
24
public class ParallelTestRunner {
25
public interface Worker {
26
void run();
27
}
28
29
private static class WorkerThread extends Thread { // Thread safety reviewed
30
private final Worker _worker;
31
private volatile Throwable _throwable;
32
33
private WorkerThread(String name, Worker worker) {
34
super(name);
35
_worker = worker;
36
}
37
38
@Override
39
public void run() {
40
try {
41
_worker.run();
42
} catch (Throwable t) {
43
_throwable = t;
44
}
45
}
46
47
public Throwable getThrowable() {
48
return _throwable;
49
}
50
}
51
52
private final List<Worker> _workers;
53
54
public ParallelTestRunner(List<Worker> workers) {
55
_workers = workers;
56
}
57
58
public void run() throws Exception {
59
final List<WorkerThread> threads = new ArrayList<>(_workers.size());
60
Throwable t = null;
61
int i = 1;
62
for (Worker worker : _workers) {
63
final WorkerThread thread = new WorkerThread("WorkerThread #" + i, worker);
64
++i;
65
threads.add(thread);
66
thread.start();
67
}
68
for (WorkerThread thread : threads) {
69
try {
70
thread.join();
71
if (t == null) {
72
t = thread.getThrowable();
73
} else {
74
final Throwable t2 = thread.getThrowable();
75
if (t2 != null) {
76
System.err.println(thread + " failed.");
77
t2.printStackTrace(System.err);
78
}
79
}
80
} catch (InterruptedException ignored) {
81
interrupt(threads);
82
}
83
}
84
if (t != null) {
85
if (t instanceof Exception) {
86
throw (Exception) t;
87
} else if (t instanceof Error) {
88
throw (Error) t;
89
} else {
90
throw new RuntimeException("Unexpected Throwable " + t.getClass().getName(), t);
91
}
92
}
93
}
94
95
private void interrupt(List<WorkerThread> threads) {
96
for (WorkerThread thread : threads) {
97
thread.interrupt();
98
}
99
}
100
}
101
102