Skip to content

Instantly share code, notes, and snippets.

@tylertreat-wf
Created November 28, 2016 17:17
Show Gist options
  • Save tylertreat-wf/b059c9da8033e270911e693da4c7b8d3 to your computer and use it in GitHub Desktop.
Save tylertreat-wf/b059c9da8033e270911e693da4c7b8d3 to your computer and use it in GitHub Desktop.
import java.util.concurrent.*;
public class ThreadPoolTest {
public static void main(String[] args) {
BlockingQueue<Runnable> queue = new SynchronousQueue<>();
ExecutorService threadPool = new LoggingThreadPoolExecutor(1, 10, 30, TimeUnit.SECONDS, queue, new BlockingRejectedExecutionHandler());
for (int i = 0; i < 1000; i++) {
threadPool.submit(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
threadPool.shutdown();
}
static class LoggingThreadPoolExecutor extends ThreadPoolExecutor {
public LoggingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
System.out.println("pool size: " + getPoolSize());
}
}
static class BlockingRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public final void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException("Interrupted while waiting to put the element", e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment