stone2083

          初識InheritableThreadLocal

          一直來只知道ThreadLocal,直到最近看slf4j MDC實現代碼的時候,才認識了InheritableThreadLocal.
          InheritableThreadLocal顧名思義,可繼承的ThreadLocal.
          看類描述:
          This class extends <tt>ThreadLocal</tt> to provide inheritance of values
           * from parent thread to child thread: when a child thread is created, the
           * child receives initial values for all inheritable thread-local variables
           * for which the parent has values.

          測試代碼:
           1 public class Test {
           2 
           3     public static void main(String[] args) {
           4         //使用ThreadLocal,父子線程之間,不共享Value
           5         final ThreadLocal<String> tl = new ThreadLocal<String>();
           6         tl.set("ThreadLocal-VAL");
           7         System.out.println("Main-1:" + tl.get());
           8         new Thread() {
           9             public void run() {
          10                 System.out.println("Child-1:" + tl.get());
          11             };
          12         }.start();
          13 
          14         //使用InheritableThreadLocal,父線程Value可讓子線程共享
          15         final ThreadLocal<String> itl = new InheritableThreadLocal<String>();
          16         itl.set("InheritableThreadLocal-VAL");
          17         System.out.println("Main-2:" + itl.get());
          18         new Thread() {
          19             public void run() {
          20                 System.out.println("Child-2:" + itl.get());
          21             };
          22         }.start();
          23 
          24     }
          25 }

          輸出內容:
          Main-1:ThreadLocal-VAL
          Main-2:InheritableThreadLocal-VAL
          Child-1:null
          Child-2:InheritableThreadLocal-VAL


          ......分隔符號......

          順帶著簡單說下MDC.(Mapped Diagnostic Context). 中文直譯太惡心了,我理解的意思是,和環境相關的上下文信息.
          比如在web應用中,我們可以把用戶的ip,訪問url等放入到這個上下文中,log打印的時候,就能得到這個信息.

          在slf4j BasicMDCAdapter實現中,就是用了InheritableThreadLocal
          1 public class BasicMDCAdapter implements MDCAdapter {
          2 
          3   private InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal();
          4   
          5   //.
          6 
          7 }

          posted on 2010-07-23 09:17 stone2083 閱讀(2592) 評論(0)  編輯  收藏 所屬分類: java

          主站蜘蛛池模板: 武功县| 宜州市| 忻城县| 阿坝县| 红安县| 郸城县| 尼勒克县| 射阳县| 左贡县| 肃北| 中超| 汾西县| 阜城县| 专栏| 临潭县| 黄大仙区| 宁城县| 宁津县| 新干县| 开原市| 页游| 五指山市| 桃江县| 宝山区| 台南县| 涪陵区| 天台县| 精河县| 修水县| 张掖市| 余江县| 雷州市| 屯门区| 长宁区| 双桥区| 东乡| 新乐市| 介休市| 汽车| 饶阳县| 三都|