zoukankan      html  css  js  c++  java
  • ThreadLocal学习记录

    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既然能解决并发出现的问题,那我们之前经常使用的synchronized或者volatile有什么区别呢。synchronized这类线程同步的机制可以解决多线程并发问题,在这种解决方案下,多个线程访问到的, 都是同一份变量的内容。为了防止在多线程访问的过程中,可能会出现并发错误。 不得不对多个线程的访问进行同步,这样也就意味着, 多个线程必须先后对变量的值进行访问或者修改,这是一种以延长访问时间来换取线程安全性的策略。

    而ThreadLocal类为每一个线程都维护了自己独有的变量拷贝。每个线程都拥有了自己独立的一个变量,竞争条件被彻底消除了,那就没有任何必要对这些线程进行同步,它们也能最大限度的由CPU调度,并发执行。并且由于每个线程在访问该变量时,读取和修改的,都是自己独有的那一份变量拷贝,变量被彻底封闭在每个访问的线程中,并发错误出现的可能也完全消除了。对比前一种方案,这是一种以空间来换取线程安全性的策略。

    使用范例

    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

  • 相关阅读:
    微信小程序---app.json中设置背景色不生效解决办法
    给网站设置ICO图标
    ajax事件(五)
    ajax关于主流中的异类:应对Opera(四)
    dashboard
    tomcat 清理日志
    jQuery datatable
    php wampserver 80 端口无法开启的解决方法
    mysql 行列转换
    jQuery-2.1.4.min.js:4 Uncaught TypeError: Illegal invocation
  • 原文地址:https://www.cnblogs.com/mingziday/p/5100768.html
Copyright © 2011-2022 走看看