如何在线程池中使用MDC?

如何在线程池中使用MDC?,第1张

如何在线程池中使用MDC?

的,这也是我遇到的常见问题。有一些解决方法(如所述手动设置),但理想情况下,您需要一种解决方案

一致地设置MDC;
避免MDC不正确但您不知道的默认错误;和
最小化线程池使用方式的更改(例如Callable,MyCallable随处可见的子类化或类似的丑陋情况)。
这是我使用的满足这三个需求的解决方案。代码应该是不言自明的。


(请注意,MoreExecutors.listeningDecorator()如果您使用Guava的,可以创建此执行程序并将其馈送到Guava的ListanableFuture。)

import org.slf4j.MDC;import java.util.Map;import java.util.concurrent.*;public class MdcThreadPoolExecutor extends ThreadPoolExecutor {    final private boolean useFixedContext;    final private Map<String, Object> fixedContext;        public static MdcThreadPoolExecutor newWithInheritedMdc(int corePoolSize, int maximumPoolSize, long keepAliveTime,     TimeUnit unit, BlockingQueue<Runnable> workQueue) {        return new MdcThreadPoolExecutor(null, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);    }        @SuppressWarnings("unchecked")    public static MdcThreadPoolExecutor newWithCurrentMdc(int corePoolSize, int maximumPoolSize, long keepAliveTime,   TimeUnit unit, BlockingQueue<Runnable> workQueue) {        return new MdcThreadPoolExecutor(MDC.getCopyOfContextMap(), corePoolSize, maximumPoolSize, keepAliveTime, unit,     workQueue);    }        public static MdcThreadPoolExecutor newWithFixedMdc(Map<String, Object> fixedContext, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {        return new MdcThreadPoolExecutor(fixedContext, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);    }    private MdcThreadPoolExecutor(Map<String, Object> fixedContext, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);        this.fixedContext = fixedContext;        useFixedContext = (fixedContext != null);    }    @SuppressWarnings("unchecked")    private Map<String, Object> getContextForTask() {        return useFixedContext ? fixedContext : MDC.getCopyOfContextMap();    }        @Override    public void execute(Runnable command) {        super.execute(wrap(command, getContextForTask()));    }    public static Runnable wrap(final Runnable runnable, final Map<String, Object> context) {        return new Runnable() { @Override public void run() {     Map previous = MDC.getCopyOfContextMap();     if (context == null) {         MDC.clear();     } else {         MDC.setContextMap(context);     }     try {         runnable.run();     } finally {         if (previous == null) {  MDC.clear();         } else {  MDC.setContextMap(previous);         }     } }        };    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5565528.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存