【发布时间】:2022-01-13 04:17:06
【问题描述】:
我想要某种方式让beforeExecute() 在每次线程执行之前在主线程上 执行:
我有以下 ThreadPoolExecutor:
public class ContextAwareThreadPool extends ThreadPoolExecutor {
public ContextAwareThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, @NotNull TimeUnit unit, @NotNull BlockingQueue<Runnable> workQueue, @NotNull ThreadFactory threadFactory, @NotNull RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
ThreadPoolContextHolder.setDatasourceForThread(t, DBContextHolder.getCurrentDb());
}
}
最大的问题是beforeExecute 在工作线程中被调用,而不是从主线程(请求线程)。 因此DBContextHolder 是main 线程中的本地线程,在worker 线程中没有设置。
在线程实际执行之前,beforeExecute 回调是否在 main 线程中执行?
在工作线程中执行此设计决策毫无意义。 如果我想在 Map 中设置某些 ThreadLocals,然后在工作线程中检索它怎么办?
【问题讨论】:
标签: java multithreading executorservice threadpoolexecutor