I need an ExecutorService implementation that can limit how many Runnables can be queued. I would also like to be able to control what happens when new runnables are submitted while the queue is already full. Ideally I'd like to be able to select a strategy but just removing the runnable at the front of the queue and placing the new one at the end of the queue would suffice. I'm sure there must be something like that already implemented and I looked around but couldn't find any.
Use DiscardOldestPolicy
:
A handler for rejected tasks that discards the oldest unhandled request and then retries execute, unless the executor is shut down, in which case the task is discarded.
and BlockingQueue
with fixed capacity:
int fixedThreadNumber = 10;
int idleSeconds = 10;
BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(10);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
fixedThreadNumber,
fixedThreadNumber,
idleSeconds, TimeUnit.SECONDS,
blockingQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
ExecutorService executor = threadPoolExecutor;