Skip to content

Commit

Permalink
limit the number of threads created when doing RunWith(ConcurrentTest…
Browse files Browse the repository at this point in the history
…Runner.class)
  • Loading branch information
tobyweston committed Sep 25, 2013
1 parent e074193 commit 08a35ff
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,28 @@

package com.google.code.tempusfugit.concurrency;

import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newFixedThreadPool;

public class ConcurrentTestRunner extends BlockJUnit4ClassRunner {

public ConcurrentTestRunner(Class<?> type) throws InitializationError {
super(type);
setScheduler(new ConcurrentScheduler(newCachedThreadPool(new ConcurrentTestRunnerThreadFactory())));
setScheduler(new ConcurrentScheduler(createExecutor(type)));
}

private static ExecutorService createExecutor(Class<?> type) {
if (type.getAnnotation(Concurrent.class) != null)
return newFixedThreadPool(type.getAnnotation(Concurrent.class).count(), new ConcurrentTestRunnerThreadFactory());
return newCachedThreadPool(new ConcurrentTestRunnerThreadFactory());
}

private static class ConcurrentTestRunnerThreadFactory implements ThreadFactory {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
Expand All @@ -30,7 +31,7 @@
* @see com.google.code.tempusfugit.concurrency.ConcurrentRule
*/
@Documented
@Target(METHOD)
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Concurrent {
int count() default 5;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.code.tempusfugit.concurrency;

import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import com.google.code.tempusfugit.temporal.Condition;
import junit.framework.AssertionFailedError;
import org.junit.AfterClass;
Expand All @@ -35,6 +36,7 @@
import static org.hamcrest.core.Is.is;

@RunWith(ConcurrentTestRunner.class)
@Concurrent(count = 5)
public class ConcurrentTestRunnerTest {

private static final Set<String> threads = synchronizedSet(new HashSet<String>());
Expand Down

0 comments on commit 08a35ff

Please sign in to comment.