使用默認的 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);
}
}
}
}