ThreadLocal的学习

本文摘自于:http://www.cnblogs.com/dolphin0520/p/3920407.html

(1)ThreadContext<T>为基于键/值对的当前线程提供了一种绑定和非绑定对象的方法。

这个类提供线程局部变量。这些变量与普通的变量不同,因为每个访问一个线程的线程(通过其get或set方法)都有自己的独立初始化变量的副本。

ThreadLocal实例通常是希望将状态与线程关联的类中的私有静态字段(例如:一个用户ID或事务ID)。每个线程都对线程本地变量的副本有一个隐式引用,

只要线程还活着,ThreadLocal实例就可以访问;在一个线程消失之后,所有线程本地实例的副本都将被垃圾收集(除非存在其他引用)。

<T>为线程中保存的对象。即一个类T是线程的一个类属性。

常用的方法有:

 1 public class ThreadLocal<T> {
 2 
 3 //设置属性
 4 
 5 public void set(T value) {
 6 Thread t = Thread.currentThread();
 7 ThreadLocalMap map = getMap(t);
 8 if (map != null)
 9 map.set(this, value);
10 else
11 createMap(t, value);
12 }
13 
14 //获取属性
15 
16 public T get() {
17 Thread t = Thread.currentThread();
18 ThreadLocalMap map = getMap(t);
19 if (map != null) {
20 ThreadLocalMap.Entry e = map.getEntry(this);
21 if (e != null)
22 return (T)e.value;
23 }
24 return setInitialValue();
25 }
26 
27 //获取线程的 ThreadLocal.ThreadLocalMap
28 
29 ThreadLocalMap getMap(Thread t) {
30 return t.threadLocals;
31 }
32 
33 }
34 
35 //新建一个线程本地的localMap
36 
37 void createMap(Thread t, T firstValue) {
38 t.threadLocals = new ThreadLocalMap(this, firstValue);
39 }

(2)使用例子:连接、会话如下:

 1 private static ThreadLocal<Connection> connectionHolder
 2 = new ThreadLocal<Connection>() {
 3 public Connection initialValue() {
 4     return DriverManager.getConnection(DB_URL);
 5 }
 6 };
 7  
 8 public static Connection getConnection() {
 9 return connectionHolder.get();
10 }
 1 private static final ThreadLocal threadSession = new ThreadLocal();
 2  
 3 public static Session getSession() throws InfrastructureException {
 4     Session s = (Session) threadSession.get();
 5     try {
 6         if (s == null) {
 7             s = getSessionFactory().openSession();
 8             threadSession.set(s);
 9         }
10     } catch (HibernateException ex) {
11         throw new InfrastructureException(ex);
12     }
13     return s;
14 }

 

原文地址:https://www.cnblogs.com/panql341/p/7169485.html