码迷,mamicode.com
首页 > 其他好文 > 详细

ThreadLocal学习记录

时间:2016-01-05 01:26:39      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

ThreadLocal简介

当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。从线程的角度看,目标变量就象是线程的本地变量,这也是类名中“Local”所要表达的意思。
ThreadLocal类接口只有4个方法:

  • void set(T value)  设置当前线程的线程局部变量的值。
  • public T get()  该方法返回当前线程所对应的线程局部变量。
  • public void remove()  将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK 5.0新增的方法。需要指出的是,当线程结束后,对应该线程的局部变量将自动被垃圾回收,所以显式调用该方法清除线程的局部变量并不是必须的操作,但它可以加快内存回收的速度。
  • protected T initialValue()  返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第1次调用get()或set(Object)时才执行,并且仅执行1次。ThreadLocal中的缺省实现直接返回一个null。

ThreadLocal原理

每个线程中都有一个独立的ThreadLocalMap副本,它所存储的值,只能被当前线程读取和修改。ThreadLocal类通过操作每一个线程特有的ThreadLocalMap副本,从而实现了变量访问在不同线程中的隔离,因为每个线程的变量都是自己特有的,看一下代码就清楚了。

/*这就是Thread类的定义,该类包含了一个局部变量threadLocals,ThreadLocal就是通过操作这个局部变量来实现器功能的*/
public class Thread implements Runnable {
  /* ThreadLocal values pertaining to this thread. This map is maintained by the ThreadLocal class. */
  ThreadLocal.ThreadLocalMap threadLocals = null
  ……
}

/*这就是ThreadLocal的实现类,我们主要看看它的get/set方法*/
public class ThreadLocal<T> { /** * Returns the value in the current thread‘s copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread‘s value of this thread-local */ public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); /*猜一猜,肯定是获取当前Thread类的局部变量threadLocals*/ if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } /** * Variant of set() to establish initialValue. Used instead * of set() in case user has overridden the set() method. * * @return the initial value */ private T setInitialValue() { T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); /*如果threadLocals不存在,就new一个,并把value塞进去*/ return value; } /** * Sets the current thread‘s copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread‘s copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); /*如果threadLocal不存在,就new一个并把value设置进去*/ } /** * Removes the current thread‘s value for this thread-local * variable. If this thread-local variable is subsequently * {@linkplain #get read} by the current thread, its value will be * reinitialized by invoking its {@link #initialValue} method, * unless its value is {@linkplain #set set} by the current thread * in the interim. This may result in multiple invocations of the * {@code initialValue} method in the current thread. * * @since 1.5 */ public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
}

ThreadLocal vs Synchronized

在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量,多个线程需要排队来访问这一个变量,“以时间换空间”。这时该变量是多个线程共享的,使用同步机制要求程序慎密地分析什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放对象锁等繁杂的问题,程序设计和编写难度相对较大。

而ThreadLocal则从另一个角度来解决多线程的并发访问。ThreadLocal会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突。因为每一个线程都拥有自己的变量副本,从而也就没有必要对该变量进行同步了。“以空间换时间”,“并发资源变得不再需要抢占了”。

使用范例

JDBC的一切行为包括事务是基于一个Connection对象控制的,获取Connection的方法需要对并发有良好的支持。否则,当一个事务提交完毕并关闭Connection之后,另一个Connection可能还正在准备提交,此时必然会导致失败。

/*这是一个普通的获取连接对象的类,用该类获取的Connection可以被多个线程共享使用*/
public class ConnectionHolder { private Map<DataSource, Connection> connectionMap = new HashMap<DataSource, Connection>(); public Connection getConnection(DataSource dataSource) throws SQLException { Connection connection = connectionMap.get(dataSource); if (connection == null || connection.isClosed()) { connection = dataSource.getConnection(); connectionMap.put(dataSource, connection); } return connection; } public void removeConnection(DataSource dataSource) { connectionMap.remove(dataSource); } } /*采用ThreadLocal类,将上面的connectionHolder副本保存在当前线程中,这样每个线程有自己的connectionHolder,就不会出现多线程冲突问题*/ public class SingleThreadConnectionHolder { private static ThreadLocal<ConnectionHolder> localConnectionHolder = new ThreadLocal<ConnectionHolder>(); public static Connection getConnection(DataSource dataSource) throws SQLException { return getConnectionHolder().getConnection(dataSource); } public static void removeConnection(DataSource dataSource) { getConnectionHolder().removeConnection(dataSource); } private static ConnectionHolder getConnectionHolder() { ConnectionHolder connectionHolder = localConnectionHolder.get(); if (connectionHolder == null) { connectionHolder = new ConnectionHolder(); localConnectionHolder.set(connectionHolder); } return connectionHolder; } }

 

 

参考文献:

http://blog.csdn.net/lufeng20/article/details/24314381

http://www.cnblogs.com/davenkin/archive/2013/02/23/java-tranaction-4.html

 

ThreadLocal学习记录

标签:

原文地址:http://www.cnblogs.com/mingziday/p/5100768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!