com.orientechnologies.orient.test.ConcurrentTestHelper Maven / Gradle / Ivy
package com.orientechnologies.orient.test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @param see {@link TestFactory}
* @author Artem Orobets (enisher-at-gmail.com)
*/
public class ConcurrentTestHelper {
private final ExecutorService executor;
private final List> futures;
private ConcurrentTestHelper(int threadCount) {
this.futures = new ArrayList>(threadCount);
this.executor = Executors.newFixedThreadPool(threadCount);
}
public static Collection test(int threadCount, TestFactory factory) {
final List> callables = prepareWorkers(threadCount, factory);
return go(callables);
}
protected static Collection go(List> workers) {
final ConcurrentTestHelper helper = new ConcurrentTestHelper(workers.size());
helper.submit(workers);
return helper.assertSuccess();
}
protected static List> prepareWorkers(int threadCount, TestFactory factory) {
final List> callables = new ArrayList>(threadCount);
for (int i = 0; i < threadCount; i++) {
callables.add(factory.createWorker());
}
return callables;
}
public static TestBuilder build() {
return new TestBuilder();
}
private Collection assertSuccess() {
try {
executor.shutdown();
assertTrue("Test threads hanged", executor.awaitTermination(30, TimeUnit.MINUTES));
List results = new ArrayList(futures.size());
List exceptions = new ArrayList();
for (Future future : futures) {
try {
results.add(future.get());
} catch (ExecutionException e) {
exceptions.add(e);
}
}
if (exceptions.isEmpty()) {
return results;
} else {
throw new CompositeException(exceptions);
}
} catch (InterruptedException e) {
fail("interrupted" + e.getMessage());
throw new RuntimeException("unreached exception", e);
}
}
private void submit(List> callables) {
for (Callable callable : callables) {
futures.add(executor.submit(callable));
}
}
}