【Java并发编程实践】— ThreadLocal分析
来源:互联网 发布:小米2s支持4g网络吗 编辑:程序博客网 时间:2024/04/29 16:18
前言
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。(注意这里说的只是“一般情况”,如果通过ThreadLocal.set() 到线程中的对象是多线程共享的同一个对象,各个线程中访问的将是同一个共享对象)。
ThreadLocal的作用
1.提供了保存对象的方法:每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2.避免参数传递的方便的对象访问方式:将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
理解ThreadLocal中提到的变量副本
“当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本” —— 并不是通过ThreadLocal.set( )实现的,而是每个线程使用“new对象”(或拷贝) 的操作来创建对象副本, 通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象(ThreadLocal实例是作为map的key来使用的)。
如果ThreadLocal.set( )进去的对象是多线程共享的同一个对象,那么ThreadLocal.get( )取得的还是这个共享对象本身 —— 那么ThreadLocal还是有并发访问问题的!
- /*
- * 如果ThreadLocal.set()进去的是一个多线程共享对象,那么Thread.get()获取的还是这个共享对象本身—————并不是该共享对象的副本。
- * 假如:其中其中一个线程对这个共享对象内容作了修改,那么将会反映到其它线程获取的共享对象中————所以说 ThreadLocal还是有并发访问问题的!
- */
- public class Test implements Runnable
- {
- private ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();
- private Person person;
- public Test(Person person)
- {
- this.person = person;
- }
- public static void main(String[] args) throws InterruptedException
- {
- //多线程共享的对象
- Person sharePerson = new Person(110,"Sone");
- Test test = new Test(sharePerson);
- System.out.println("sharePerson原始内容:"+sharePerson);
- Thread th = new Thread(test);
- th.start();
- th.join();
- //通过ThreadLocal获取对象
- Person localPerson = test.getPerson();
- System.out.println("判断localPerson与sharePerson的引用是否一致:"+(localPerson==localPerson));
- System.out.println("sharePerson被改动之后的内容:"+sharePerson);
- }
- @Override
- public void run()
- {
- String threadName = Thread.currentThread().getName();
- System.out.println(threadName+":Get a copy of the variable and change!!!");
- Person p = getPerson();
- p.setId(741741);
- p.setName("Boy");
- }
- public Person getPerson(){
- Person p = (Person)threadLocal.get();
- if (p==null)
- {
- p= this.person;
- //set():进去的是多线程共享的对象
- threadLocal.set(p);
- }
- return p;
- }
- }
理解Thread和 ThreadLocal对变量的引用关系
实际上Thread和ThreadLocal对变量引用关系就像是坐标系中的X轴和Y轴,是从两个维度上来组织对变量的引用的。
1.首先说Thread:
我们知道一个ThreadOne的执行会贯穿多个方法MethodA、MethodB、MethodC这些方法可能分布于不同的类实例。假设,这些方法分别使用了ThreadLocalA、ThreadLocalB、ThreadLocalC来保存线程本地变量,那么这些变量都存于ThreadOne的Map中,并使用各自的ThreadLocal实例作为key。 因此,可以认为,借助ThreanLocal的set方法,在X轴上,Thread横向关联同一线程上下文中来自多个Method的变量引用副本。
2.接着说ThreadLocal:
一个MethodA中的X变量将被多个线程ThreadOne、ThreadTwo、ThreadThree所访问。假设MethodA使用ThreadLocal存储X,通过set方法,以ThreadLocal作为key值,将不同线程来访时的不同的变量值引用保存于ThreadOne、ThreadTwo、ThreadThree的各自线程上下文中,确保每个线程有自己的一个变量值。因此,可以认为,ThreadLocal是以Method为Y轴,纵向关联了处于同一方法中的不同线程上的变量。
ThreadLocal的应用
下面来看一个hibernate中典型的ThreadLocal的应用:
- private static final ThreadLocal threadSession = new ThreadLocal();
- public static Session getSession() throws InfrastructureException {
- Session s = (Session) threadSession.get();
- try {
- if (s == null) {
- s = getSessionFactory().openSession();
- threadSession.set(s);
- }
- } catch (HibernateException ex) {
- throw new InfrastructureException(ex);
- }
- return s;
- }
可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值(session)的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。
试想如果不用ThreadLocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。
当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。
ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。
ThreadLocal源码分析
下面来看看ThreadLocal的实现原理(JDK1.6源码)
- public class ThreadLocal<T> {
- /**
- * ThreadLocals rely on per-thread linear-probe hash maps attached
- * to each thread (Thread.threadLocals and
- * inheritableThreadLocals). The ThreadLocal objects act as keys,
- * searched via threadLocalHashCode. This is a custom hash code
- * (useful only within ThreadLocalMaps) that eliminates collisions
- * in the common case where consecutively constructed ThreadLocals
- * are used by the same threads, while remaining well-behaved in
- * less common cases.
- */
- private final int threadLocalHashCode = nextHashCode();
- /**
- * The next hash code to be given out. Updated atomically. Starts at
- * zero.
- */
- private static AtomicInteger nextHashCode =
- new AtomicInteger();
- /**
- * The difference between successively generated hash codes - turns
- * implicit sequential thread-local IDs into near-optimally spread
- * multiplicative hash values for power-of-two-sized tables.
- */
- private static final int HASH_INCREMENT = 0x61c88647;
- /**
- * Returns the next hash code.
- */
- private static int nextHashCode() {
- return nextHashCode.getAndAdd(HASH_INCREMENT);
- }
- /**
- * Returns the current thread's "initial value" for this
- * thread-local variable. This method will be invoked the first
- * time a thread accesses the variable with the {@link #get}
- * method, unless the thread previously invoked the {@link #set}
- * method, in which case the <tt>initialValue</tt> method will not
- * be invoked for the thread. Normally, this method is invoked at
- * most once per thread, but it may be invoked again in case of
- * subsequent invocations of {@link #remove} followed by {@link #get}.
- *
- * <p>This implementation simply returns <tt>null</tt>; if the
- * programmer desires thread-local variables to have an initial
- * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be
- * subclassed, and this method overridden. Typically, an
- * anonymous inner class will be used.
- *
- * @return the initial value for this thread-local
- */
- protected T initialValue() {
- return null;
- }
- /**
- * Creates a thread local variable.
- */
- public ThreadLocal() {
- }
- /**
- * 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);
- if (map != null) {
- ThreadLocalMap.Entry e = map.getEntry(this);
- if (e != null)
- return (T)e.value;
- }
- 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);
- 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);
- }
- /**
- * 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
- * <tt>initialValue</tt> method in the current thread.
- *
- * @since 1.5
- */
- public void remove() {
- ThreadLocalMap m = getMap(Thread.currentThread());
- if (m != null)
- m.remove(this);
- }
- /**
- * Get the map associated with a ThreadLocal. Overridden in
- * InheritableThreadLocal.
- *
- * @param t the current thread
- * @return the map
- */
- ThreadLocalMap getMap(Thread t) {
- return t.threadLocals;
- }
- /**
- * Create the map associated with a ThreadLocal. Overridden in
- * InheritableThreadLocal.
- *
- * @param t the current thread
- * @param firstValue value for the initial entry of the map
- * @param map the map to store.
- */
- void createMap(Thread t, T firstValue) {
- t.threadLocals = new ThreadLocalMap(this, firstValue);
- }
- /**
- * Factory method to create map of inherited thread locals.
- * Designed to be called only from Thread constructor.
- *
- * @param parentMap the map associated with parent thread
- * @return a map containing the parent's inheritable bindings
- */
- static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
- return new ThreadLocalMap(parentMap);
- }
- /**
- * Method childValue is visibly defined in subclass
- * InheritableThreadLocal, but is internally defined here for the
- * sake of providing createInheritedMap factory method without
- * needing to subclass the map class in InheritableThreadLocal.
- * This technique is preferable to the alternative of embedding
- * instanceof tests in methods.
- */
- T childValue(T parentValue) {
- throw new UnsupportedOperationException();
- }
- static class ThreadLocalMap {
- ......
- }
- }
可以看到ThreadLocal类中的变量只有这3个int型:
- private final int threadLocalHashCode = nextHashCode();
- private static AtomicInteger nextHashCode =
- new AtomicInteger();
- private static final int HASH_INCREMENT = 0x61c88647;
而作为ThreadLocal实例的变量只有 threadLocalHashCode 这一个,nextHashCode 和HASH_INCREMENT 是ThreadLocal类的静态变量,实际上HASH_INCREMENT是一个常量,表示了连续分配的两个ThreadLocal实例的threadLocalHashCode值的增量,而nextHashCode 的表示了即将分配的下一个ThreadLocal实例的threadLocalHashCode 的值。
可以来看一下创建一个ThreadLocal实例即new ThreadLocal()时做了哪些操作,从上面看到构造函数ThreadLocal()里什么操作都没有,唯一的操作是这句:
- private final int threadLocalHashCode = nextHashCode();
- private static int nextHashCode() {
- return nextHashCode.getAndAdd(HASH_INCREMENT);
- }
因此ThreadLocal实例的变量只有这个threadLocalHashCode,而且是final的,用来区分不同的ThreadLocal实例,ThreadLocal类主要是作为工具类来使用,那么ThreadLocal.set()进去的对象是放在哪儿的呢?
看一下上面的set()方法,两句合并一下成为:
- ThreadLocalMap map = Thread.currentThread().threadLocals;
- public class Thread implements Runnable {
- ......
- /* ThreadLocal values pertaining to this thread. This map is maintained
- * by the ThreadLocal class. */
- ThreadLocal.ThreadLocalMap threadLocals = null;
- ......
- }
再看这句:
- if (map != null)
- map.set(this, value);
也就是将该ThreadLocal实例作为key,要保持的对象作为值,设置到当前线程的ThreadLocalMap 中,get()方法同样大家看了代码也就明白了,ThreadLocalMap 类的代码太多了,我就不帖了,自己去看源码吧。
写了这么多,也不知讲明白了没有,有什么不当的地方还请大家指出来。
转载地址:http://www.iteye.com/topic/103804
- 【Java并发编程实践】— ThreadLocal分析
- 【Java并发编程实践】— ThreadLocal分析
- java并发编程实践 ThreadLocal
- Java并发编程实践之ThreadLocal变量
- Java并发编程—ThreadLocal
- Java 并发编程深入学习——ThreadLocal 原理分析
- 【Java并发编程】深入分析ThreadLocal(八)
- Java并发编程-ThreadLocal
- java并发编程---ThreadLocal
- Java并发编程:ThreadLocal
- Java并发编程:ThreadLocal
- java并发编程--ThreadLocal的用法和分析
- java并发编程--ThreadLocal的用法和分析
- Java 并发 ---ThreadLocal源码分析
- java并发编程实战 ThreadLocal
- Java 并发编程--ThreadLocal类
- Java并发编程基础知识ThreadLocal
- 《Java并发编程实践》
- java IO
- ArrayList容器浅析
- eclipse集成SVN同步忽略target
- repair failure修复坏块
- OpenStack安装后的验证/初始化脚本
- 【Java并发编程实践】— ThreadLocal分析
- app ipa还原png 脚本
- Android 以singleInstance模式加载的Activity怎么接收以putExtra方式传递过来参数
- 实例解析UML图形中UML用例图和类图用法
- 二叉排序树C实现
- Windows下PHP安装配置
- codeforces 229C
- js面向对象编程,定义类的四种方法
- 理想、激情、生存—— 一位技术管理人员的20年工作经历和感悟