我们在线程局部变量中存储了一些值,并且我们在Spring ThreadPoolTaskExecutor中使用了线程池,因此一旦执行任务,我们就必须清除线程局部变量。我们尝试为Runnable提供自定义的ThreadFactory和包装器,以查看执行任务后是否可以清除线程本地。但是runnable.run()之后的行永远不会执行,请参见下面的代码。想知道我做错了什么还是我误解了什么以及实现我想要的正确方法,即清除线程池环境中的线程局部变量。
// ThreadPoolTaskExecutor configuration
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(100);
executor.setMaxPoolSize(1000);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.setThreadFactory(new CustomThreadFactory());
executor.initialize();
return executor;
}
// Custom thread factory
public class CustomThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
return new Thread(new CustomRunnable(r));
}
public static class CustomRunnable implements Runnable {
private Runnable runnable;
protected CustomRunnable(Runnable runnable) {
super();
this.runnable = runnable;
}
@Override
public void run() {
System.out.println("*******START*******");
this.runnable.run();
// I thought we could clear the thread locals here but this line is never executed
System.out.println("*******FINISH*******");
}
}
}