Site Search:

TestThreadPool.java

 TestThreadPool.java

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.junit.Assert.*;

/**
* TestingThreadFactory
* <p/>
* Testing thread pool expansion
*
*/
public class TestThreadPool {

private final TestingThreadFactory threadFactory = new TestingThreadFactory();
public static void main(String...args) throws InterruptedException {
TestThreadPool ttp = new TestThreadPool();
ttp.testPoolExpansion();
}
public void testPoolExpansion() throws InterruptedException {
int MAX_SIZE = 10;
//ExecutorService exec = Executors.newFixedThreadPool(MAX_SIZE);
ExecutorService exec = new ThreadPoolExecutor(
MAX_SIZE, MAX_SIZE, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory // Use the TestingThreadFactory here
);

for (int i = 0; i < 100 * MAX_SIZE; i++)
exec.execute(new Runnable() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
for (int i = 0;
i < 20 && threadFactory.numCreated.get() < MAX_SIZE;
i++)
Thread.sleep(100);
assertEquals(threadFactory.numCreated.get(), MAX_SIZE);
exec.shutdownNow();
}
}

class TestingThreadFactory implements ThreadFactory {
public final AtomicInteger numCreated = new AtomicInteger();
private final ThreadFactory factory = Executors.defaultThreadFactory();

public Thread newThread(Runnable r) {
numCreated.incrementAndGet();
return factory.newThread(r);
}
}

This test uses a TestingThreadFactory that maintains a count of created threads, so that test cases can verify the number of threads created during a test run.

No comments:

Post a Comment