初識(shí)InheritableThreadLocal
一直來只知道ThreadLocal,直到最近看slf4j MDC實(shí)現(xiàn)代碼的時(shí)候,才認(rèn)識(shí)了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.
* 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.
測(cè)試代碼:
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 }
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 }
輸出內(nèi)容:
Main-1:ThreadLocal-VAL
Main-2:InheritableThreadLocal-VAL
Child-1:null
Child-2:InheritableThreadLocal-VAL
......分隔符號(hào)......
順帶著簡單說下MDC.(Mapped Diagnostic Context). 中文直譯太惡心了,我理解的意思是,和環(huán)境相關(guān)的上下文信息.
比如在web應(yīng)用中,我們可以把用戶的ip,訪問url等放入到這個(gè)上下文中,log打印的時(shí)候,就能得到這個(gè)信息.
在slf4j BasicMDCAdapter實(shí)現(xiàn)中,就是用了InheritableThreadLocal
1 public class BasicMDCAdapter implements MDCAdapter {
2
3 private InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal();
4
5 //
.
6
7 }
2
3 private InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal();
4
5 //

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