总结:请使用TransmittableThreadLocal
或使用下文的方法
ThreadLocal是以线程为key的,而线程池里面的线程是会被重新利用的,会导致ThreadLocal出现意料之外的事件。
比如可能会导致在SAAS中的串库。
解决办法如下:
@Slf4j
public class HiThreadPoolExecutor extends ThreadPoolExecutor {
private Map<Integer, Thread> parentThreadMap = Collections.synchronizedMap(new LinkedHashMap<>());
public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
public void execute(Runnable command) {
Thread parent = Thread.currentThread();
// 调用execute方法时,保存当前线程的副本
parentThreadMap.put(command.hashCode(), new Thread(parent));
super.execute(command);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
try {
Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocals.setAccessible(true);
// 取出execute方法中保存的对应父线程副本,并将该副本的inheritableThreadLocals(ThreadLocal变量存放地)设置到即将执行的线程中
Object value = inheritableThreadLocals.get(parentThreadMap.remove(r.hashCode()));
if (value != null) inheritableThreadLocals.set(t, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
log.error("线程池错误" + HiThreadPoolExecutor.class.getName(), e);
}
}
}
原理是利用反射,在线程池提交任务时,将当前环境下的inheritableThreadLocals
保存,并在执行线程任务时,提取inheritableThreadLocals
并设置到子线程中。
需要注意的是execute
方法是在submit
时调用的, 而beforeExecute
方法是在执行线程任务之前调用的。