ThreadPoolTaskExecutor
继我们之前聊到了 踩坑之SimpleAsyncTaskExecutor
那我们可以使用什么类来替代此类实现上下文的传递呢?
ThreadPoolTaskExecutor
- 我们通过TaskDecorator接口反查,可以发现ThreadPoolTaskExecutor类也在使用这个接口;我们通过这个类申明一个Bean:
@Bean("taskExecutor")
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(Math.min(16, Runtime.getRuntime().availableProcessors() * 2));
executor.setMaxPoolSize(executor.getCorePoolSize() * 2);
executor.setThreadNamePrefix("async-");
executor.setTaskDecorator(runnable -> {
SecurityContext context = SecurityContextHolder.getContext();
return () -> {
try {
SecurityContextHolder.setContext(context);
runnable.run();
} finally {
SecurityContextHolder.clearContext();
}
};
});
executor.initialize();
return executor;
}
在对一系列属性设置之后,通过initialize方法完成初始化;
- 看下初始化方法内部做了什么?
@Nullable
// 内部维护了ExecutorService
private ExecutorService executor;
public void initialize() {
if (logger.isInfoEnabled()) {
logger.info("Initializing ExecutorService" + (this.beanName != null ? " '" + this.beanName + "'" : ""));
}
// 设置线程名字
if (!this.threadNamePrefixSet && this.beanName != null) {
setThreadNamePrefix(this.beanName + "-");
}
// 又执行了initializeExecutor
this.executor = initializeExecutor(this.threadFactory, this.rejectedExecutionHandler);
}
看下initializeExecutor
protected ExecutorService initializeExecutor(
ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
// 创建队列
BlockingQueue<Runnable> queue = createQueue(this.queueCapacity);
// 定义线程池
ThreadPoolExecutor executor;
// 如果实现了装饰接口
if (this.taskDecorator != null) {
// new了一个正常的线程池,区别是重写了execute方法
executor = new ThreadPoolExecutor(
this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
queue, threadFactory, rejectedExecutionHandler) {
@Override
public void execute(Runnable command) {
// 重写execute方法, 首先执行了装饰接口实现
Runnable decorated = taskDecorator.decorate(command);
if (decorated != command) {
// 放到弱引用的map中,与此文无关,暂不赘述
decoratedTaskMap.put(decorated, command);
}
// 执行线程池的execute方法
super.execute(decorated);
}
};
}
else {
executor = new ThreadPoolExecutor(
this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
queue, threadFactory, rejectedExecutionHandler);
}
if (this.allowCoreThreadTimeOut) {
executor.allowCoreThreadTimeOut(true);
}
this.threadPoolExecutor = executor;
return executor;
}
-
其实在SimpleAsyncTaskExecutor类中作者也标识了这个类:
* * @author Juergen Hoeller * @since 2.0 * @see #setConcurrencyLimit * @see SyncTaskExecutor * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor 标识了这个类 * @see org.springframework.scheduling.commonj.WorkManagerTaskExecutor */ @SuppressWarnings("serial") public class SimpleAsyncTaskExecutor extends CustomizableThreadCreator
时在中春,阳和方起