Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executor Thread Pool - limit queue size and dequeue oldest

I am using a fixed thread pool for a consumer of produced messages within a spring boot application. My producer is producing (a lot) faster than the producer is able to handle a message, therefore the queue of the thread pool seems to be "flooding".

What would be the best way to limit the queue size? The intended queue behaviour would be "if the queue is full, remove the head and insert the new Runnable". Is it possible to configure Executors thread pool like this?

like image 560
user6903701 Avatar asked Nov 10 '18 07:11

user6903701


1 Answers

ThreadPoolExecutor supports this function via ThreadPoolExecutor.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.

You need to construct the pool with this policy mannully, for exmaple:

int poolSize = ...;
int queueSize = ...;
RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardOldestPolicy();

ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<>(queueSize),
    handler);
like image 88
xingbin Avatar answered Oct 05 '22 19:10

xingbin