ThreadPoolExecutor without a Queue
You can use a SynchronousQueue in your ThreadPoolExector which is a queue which holds no objects. The cached thread pool uses this because it creates new threads on demand.
If it cannot be queued but I would suggest using the RejectedExecutionHandler to run the task in the current thread. This way it will always be run "immediately".
BTW: It would be useful to make it clear why you want to do this.
I want to create a fixed-size thread pool that admits no task into its queue.
For posterity, if you need a thread-pool that does not have a queue and does run all of the jobs (slightly different than the OP), then you can use the SynchronousQueue
which will block until a thread is ready for the job. The trick is to use a RejectedExecutionHandler
which calls put(...)
on the queue which will block.
threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
keepAliveTime, unit, new SynchronousQueue<Runnable>(),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable runnable,
ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new RejectedExecutionException("pool already shutdown");
}
try {
// this needs to be put(...) and not add(...)
executor.getQueue().put(runnable);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
You will be able to submit jobs until the maximumPoolSize
number of threads is reached and then the submitting will block until a job finishes and a thread is available to de-queue from the SynchronousQueue
.
NOTE: After the thread pool is shutdown any Runnable
s that are submitted must throw RejectedExecutionException
otherwise they will block indefinitely in executor.getQueue().put(...)
waiting for an idle thread.