栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在线程池中使用MDC?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在线程池中使用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);         }     } }        };    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/574289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号