It seems to be impossible to make a cached thread pool with a limit to the number of threads that it can create.
Here is how static Executors.newCachedThreadPool is
Here is another solution. I think this solution behaves as you want it to (though not proud of this solution):
final LinkedBlockingQueue queue = new LinkedBlockingQueue() {
public boolean offer(Runnable o) {
if (size() > 1)
return false;
return super.offer(o);
};
public boolean add(Runnable o) {
if (super.offer(o))
return true;
else
throw new IllegalStateException("Queue full");
}
};
RejectedExecutionHandler handler = new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
queue.add(r);
}
};
dbThreadExecutor =
new ThreadPoolExecutor(min, max, 60L, TimeUnit.SECONDS, queue, handler);