Executor Thread Pool - 限制队列大小并使最旧的出队

use*_*701 7 java queue multithreading threadpoolexecutor

我在 Spring Boot 应用程序中为生成的消息的使用者使用固定的线程池。我的生产者生产(很多)比生产者能够处理消息的速度快,因此线程池的队列似乎“泛滥”。

限制队列大小的最佳方法是什么?预期的队列行为将是“如果队列已满,则移除头部并插入新的 Runnable”。是否可以像这样配置 Executors 线程池?

孙兴斌*_*孙兴斌 6

ThreadPoolExecutor通过ThreadPoolExecutor.DiscardOldestPolicy以下方式支持此功能:

被拒绝任务的处理程序,丢弃最早的未处理请求,然后重试执行,除非执行程序关闭,在这种情况下任务将被丢弃。

您需要使用此策略手动构建池,例如:

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

ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<>(queueSize),
    handler);
Run Code Online (Sandbox Code Playgroud)