使用默认的 ThreadPoolExecutor.DiscardPolicy, 直接丢弃当前超出队列的数据。
使用自定义的处理器,该处理器会阻塞地向BlockQueen 放数据,直到有剩余空间可用(注意这可能导致很多线程处于 executor.getQueue().put(r) 方法线程等待中)。
/**
* default executor is SimpleAsyncTaskExecutor
* 配置参考 https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/spring-boot-features.html#boot-features-task-execution-scheduling
*/
@Slf4j
@Configuration
@EnableAsync
public class AsyncConf {
@Primary
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setQueueCapacity(6000);
executor.setKeepAliveSeconds(10);
executor.setThreadNamePrefix("My Async Thread-");
executor.setRejectedExecutionHandler(new RejectedExecutionHandlerImpl());
executor.initialize();
return executor;
}
public static class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
//阻塞当前线程
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException("There was an unexpected InterruptedException whilst waiting to add a Runnable in the executor's blocking queue", e);
}
}
}
}