Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save vegaasen/b723b807a783a9ed2c42 to your computer and use it in GitHub Desktop.

Select an option

Save vegaasen/b723b807a783a9ed2c42 to your computer and use it in GitHub Desktop.
package com.telenor.runners;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A simple Multi-threaded runner. Haven't you always wanted that extra speed of your JUnit tests?
* Use this thingie instead, then! :-)
* Add:
* @RunWith(NotSingleThreadedRunner.class)
*
* @author <a href="[email protected]">t769765</a>
*/
public final class NotSingleThreadedRunner extends BlockJUnit4ClassRunner {
private static final int MAX_THREADS = 8;
private static final int SLEEP_TIME = 25;
private static final int INITIAL_VALUE = 0;
private AtomicInteger numThreads;
public NotSingleThreadedRunner(Class<?> klass) throws InitializationError {
super(klass);
numThreads = new AtomicInteger(INITIAL_VALUE);
}
@Override
protected void runChild(final FrameworkMethod method, final RunNotifier notifier) {
while (numThreads.get() > MAX_THREADS) {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
numThreads.incrementAndGet();
new Thread(new Test(method, notifier)).start();
}
@Override
protected Statement childrenInvoker(final RunNotifier notifier) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
NotSingleThreadedRunner.super.childrenInvoker(notifier).evaluate();
while (numThreads.get() > 0) {
Thread.sleep(SLEEP_TIME);
}
}
};
}
private final class Test implements Runnable {
private final FrameworkMethod method;
private final RunNotifier notifier;
public Test(final FrameworkMethod method, final RunNotifier notifier) {
this.method = method;
this.notifier = notifier;
}
@Override
public void run() {
NotSingleThreadedRunner.super.runChild(method, notifier);
numThreads.decrementAndGet();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment