面试

ThreadLocal简析

2017-06-05  本文已影响9人  老羊_肖恩

简介

  java.lang.ThreadLocal是自JDK1.2就开始提供的一个线程局部变量(thread-local variables),ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。ThreadLocal采用“锁分离”的思想,为每个线程独立的拷贝变量的初始副本,使得每个线程可以独立地对ThreadLocal变量进行修改,而不至于互相影响。每个线程持有一个线程本地变量的副本的隐式引用,只要线程还活着,该实例就可以访问;当线程在线程结束后,线程中所有的线程局部变量实例会被垃圾回收,除非仍有指向这个副本的引用存在。
  ThreadLocal并不是为了解决多个线程间共享变量的安全问题。ThreadLocal采用“锁分离”的策略,为共享变量在每一个线程中都创建一个独立的副本,这样每个线程都可以独立的访问和修改自己内部的副本变量。该副本变量在线程内部任何地方都可以使用,线程之间互不影响,这样一来就不存在线程安全问题,也不会严重影响程序执行性能。
  但是要注意,虽然ThreadLocal能够解决上面说的问题,但是由于在每个线程中都创建了副本,所以要考虑它对资源的消耗,比如内存的占用会比不使用ThreadLocal要大。

方法摘要

方法 | 摘要
----|------|----
T get() | 返回此线程局部变量的当前线程副本中的值
T initialValue() |返回此线程局部变量的当前线程的“初始值”
void remove() | 移除此线程局部变量当前线程的值。
void set(T value) | 将此线程局部变量的当前线程副本中的值设置为指定值


/**
     * 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) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

  方法分析:该方法返回当前线程中的 thread-local变量的值,如果这个变量没有值,会执行初始化方法setInitialValue(),获取当前线程中的ThreadLocalMap,如果该引用为null,则为当前线程创建ThreadLocalMap。

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;
    }

protected T initialValue() {
        return null;
    }

  方法分析:这是一个protected修饰的方法。返回当前线程的thread-local变量的初始值。默认返回null;


/**
     * 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);
    }

  方法分析:首先获取当前线程的ThreadLocalMap,如果为null,则为当前线程创建ThreadLocalMap,否则调用ThreadLocalMap的set()方法将value值set进当前的ThreadLocalMap中。ThreadLocalMap 的set()方法实现如下:

 /**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

/**
     * 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);
     }

  方法分析:将当前线程的thread-local变量值从ThreadLocalMap中移除。该方法是JDK1.5以后提供的。

实现原理分析

  ThreadLocal的实现主要是依赖于内部一个静态的定制类ThreadLocalMap,该Map用于维护线程的thread-local局部变量。而每个线程中会存在一个ThreadLocal.ThreadLocalMap的引用。

 /**
     * ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     */
static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
        //....
        }
        ....
}
//------------------------------------------------------------------------
/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

  当对线程的thread-loca变量进行操作时,实际上是对ThreadLocal. ThreadLocalMap进行相关操作。

/**
     * 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;
    }

实例

class RunnableDemo implements Runnable {
   int counter;
   ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();

   public void run() {     
      counter++;
      if(threadLocalCounter.get() != null){
         threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
      }else{
         threadLocalCounter.set(0);
      }
      System.out.println("Counter: " + counter);
      System.out.println("threadLocalCounter: " + threadLocalCounter.get());
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo commonInstance = new RunnableDemo();

      Thread t1 = new Thread( commonInstance);
      Thread t2 = new Thread( commonInstance);

      t1.start();
      t2.start();
     
      // wait for threads to end
      try {
         t1.join();
         t2.join();
      }catch( Exception e) {
         System.out.println("Interrupted");
      }
   }
}

将产生如下结果:

Counter: 1
threadLocalCounter: 0
Counter: 2
threadLocalCounter: 0
上一篇下一篇

猜你喜欢

热点阅读