Path: blob/trunk/java/test/org/openqa/selenium/ParallelTestRunner.java
1865 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617package org.openqa.selenium;1819import java.util.ArrayList;20import java.util.List;2122/** Utility class for concurrency tests. */23public class ParallelTestRunner {24public interface Worker {25void run();26}2728private static class WorkerThread extends Thread { // Thread safety reviewed29private final Worker _worker;30private volatile Throwable _throwable;3132private WorkerThread(String name, Worker worker) {33super(name);34_worker = worker;35}3637@Override38public void run() {39try {40_worker.run();41} catch (Throwable t) {42_throwable = t;43}44}4546public Throwable getThrowable() {47return _throwable;48}49}5051private final List<Worker> _workers;5253public ParallelTestRunner(List<Worker> workers) {54_workers = workers;55}5657public void run() throws Exception {58final List<WorkerThread> threads = new ArrayList<>(_workers.size());59Throwable t = null;60int i = 1;61for (Worker worker : _workers) {62final WorkerThread thread = new WorkerThread("WorkerThread #" + i, worker);63++i;64threads.add(thread);65thread.start();66}67for (WorkerThread thread : threads) {68try {69thread.join();70if (t == null) {71t = thread.getThrowable();72} else {73final Throwable t2 = thread.getThrowable();74if (t2 != null) {75System.err.println(thread + " failed.");76t2.printStackTrace(System.err);77}78}79} catch (InterruptedException ignored) {80interrupt(threads);81}82}83if (t != null) {84if (t instanceof Exception) {85throw (Exception) t;86} else if (t instanceof Error) {87throw (Error) t;88} else {89throw new RuntimeException("Unexpected Throwable " + t.getClass().getName(), t);90}91}92}9394private void interrupt(List<WorkerThread> threads) {95for (WorkerThread thread : threads) {96thread.interrupt();97}98}99}100101102