前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ThreadLocal源码分析

ThreadLocal源码分析

作者头像
曾大稳
发布2018-09-11 10:37:52
3090
发布2018-09-11 10:37:52
举报
文章被收录于专栏:曾大稳的博客曾大稳的博客

ThreadLocal的作用是保证当前线程对象的唯一性,在android源码中有大量的应用,是怎么实现的呢?

set:

代码语言:javascript
复制
/**
     * 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();
        //获取Thread里面的ThreadLocal.ThreadLocalMap对象
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            //创建ThreadLocal.ThreadLocalMap对象
            createMap(t, value);
    }
    
    
     /**
     * 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;
    }
    
    
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
     //Thread对象中
    ThreadLocal.ThreadLocalMap threadLocals = null;

createMap函数:

代码语言:javascript
复制

/**
     * 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
     */
    void createMap(Thread t, T firstValue) {
        //给当前线程的threadLocals赋值
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

ThreadLocalMap:

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
        
        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;
        
         /**
         * The number of entries in the table.
         */
        private int size = 0;
    
     /**
         * Construct a new map initially containing (firstKey, firstValue).
         * ThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
         */
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            //创建Entry对象  初始化容积 16
            table = new Entry[INITIAL_CAPACITY];
            //根据ThreadLocal的hash值找到对应的位置
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            //设置对应的object   
            //点进Entry可以看到,其实Entry是将ThradLocal包装成弱引用的一个扩充
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
        
         /**
         * 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<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

ThreadLocalset函数

代码语言:javascript
复制
/**
        * 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;
           //根据当前ThreadLocal得到对应的位置
           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;
               }
           }
           //如果当前的对象没有在当前线程存储过,那么将进行Entry初始化、赋值和存储
           tab[i] = new Entry(key, value);
           int sz = ++size;
           //回收旧的对象   //如果阈值threshold超过2/3的值就回收并且cleanSomeSlots返回false
           if (!cleanSomeSlots(i, sz) && sz >= threshold)
               rehash();
       }
       
       
       
        /**
        * Replace a stale entry encountered during a set operation
        * with an entry for the specified key.  The value passed in
        * the value parameter is stored in the entry, whether or not
        * an entry already exists for the specified key.
        *
        * As a side effect, this method expunges all stale entries in the
        * "run" containing the stale entry.  (A run is a sequence of entries
        * between two null slots.)
        *
        * @param  key the key
        * @param  value the value to be associated with key
        * @param  staleSlot index of the first stale entry encountered while
        *         searching for key.
        */
       private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                      int staleSlot) {
           Entry[] tab = table;
           int len = tab.length;
           Entry e;

           // Back up to check for prior stale entry in current run.
           // We clean out whole runs at a time to avoid continual
           // incremental rehashing due to garbage collector freeing
           // up refs in bunches (i.e., whenever the collector runs).
           int slotToExpunge = staleSlot;
           for (int i = prevIndex(staleSlot, len);
                (e = tab[i]) != null;
                i = prevIndex(i, len))
               if (e.get() == null)
                   slotToExpunge = i;

           // Find either the key or trailing null slot of run, whichever
           // occurs first
           for (int i = nextIndex(staleSlot, len);
                (e = tab[i]) != null;
                i = nextIndex(i, len)) {
               ThreadLocal<?> k = e.get();

               // If we find key, then we need to swap it
               // with the stale entry to maintain hash table order.
               // The newly stale slot, or any other stale slot
               // encountered above it, can then be sent to expungeStaleEntry
               // to remove or rehash all of the other entries in run.
               if (k == key) {
                   e.value = value;

                   tab[i] = tab[staleSlot];
                   tab[staleSlot] = e;

                   // Start expunge at preceding stale entry if it exists
                   if (slotToExpunge == staleSlot)
                       slotToExpunge = i;
                   cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                   return;
               }

               // If we didn't find stale entry on backward scan, the
               // first stale entry seen while scanning for key is the
               // first still present in the run.
               if (k == null && slotToExpunge == staleSlot)
                   slotToExpunge = i;
           }

           // If key not found, put new entry in stale slot
           tab[staleSlot].value = null;
           tab[staleSlot] = new Entry(key, value);

           // If there are any other stale entries in run, expunge them
           if (slotToExpunge != staleSlot)
               cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
       }

   
   
   /**
        * Heuristically scan some cells looking for stale entries.
        * This is invoked when either a new element is added, or
        * another stale one has been expunged. It performs a
        * logarithmic number of scans, as a balance between no
        * scanning (fast but retains garbage) and a number of scans
        * proportional to number of elements, that would find all
        * garbage but would cause some insertions to take O(n) time.
        *
        * @param i a position known NOT to hold a stale entry. The
        * scan starts at the element after i.
        *
        * @param n scan control: {@code log2(n)} cells are scanned,
        * unless a stale entry is found, in which case
        * {@code log2(table.length)-1} additional cells are scanned.
        * When called from insertions, this parameter is the number
        * of elements, but when from replaceStaleEntry, it is the
        * table length. (Note: all this could be changed to be either
        * more or less aggressive by weighting n instead of just
        * using straight log n. But this version is simple, fast, and
        * seems to work well.)
        *
        * @return true if any stale entries have been removed.
        */
       private boolean cleanSomeSlots(int i, int n) {
           boolean removed = false;
           Entry[] tab = table;
           int len = tab.length;
           do {
               i = nextIndex(i, len);
               Entry e = tab[i];
               if (e != null && e.get() == null) {
                   n = len;
                   removed = true;
                   i = expungeStaleEntry(i);
               }
           } while ( (n >>>= 1) != 0);
           return removed;
       }
       
       
       
       /**
        * Expunge a stale entry by rehashing any possibly colliding entries
        * lying between staleSlot and the next null slot.  This also expunges
        * any other stale entries encountered before the trailing null.  See
        * Knuth, Section 6.4
        *
        * @param staleSlot index of slot known to have null key
        * @return the index of the next null slot after staleSlot
        * (all between staleSlot and this slot will have been checked
        * for expunging).
        */
       private int expungeStaleEntry(int staleSlot) {
           Entry[] tab = table;
           int len = tab.length;

           // expunge entry at staleSlot
           tab[staleSlot].value = null;
           tab[staleSlot] = null;
           size--;

           // Rehash until we encounter null
           Entry e;
           int i;
           for (i = nextIndex(staleSlot, len);
                (e = tab[i]) != null;
                i = nextIndex(i, len)) {
               ThreadLocal<?> k = e.get();
               if (k == null) {
                   e.value = null;
                   tab[i] = null;
                   size--;
               } else {
                   int h = k.threadLocalHashCode & (len - 1);
                   if (h != i) {
                       tab[i] = null;

                       // Unlike Knuth 6.4 Algorithm R, we must scan until
                       // null because multiple entries could have been stale.
                       while (tab[h] != null)
                           h = nextIndex(h, len);
                       tab[h] = e;
                   }
               }
           }
           return i;
       }

总结:

  1. 一个线程存在一个ThreadLocal.ThreadLocalMap对象,存储的对象被封装成一个ThreadLocal作为key的弱引用扩展对象Entry,是ThreadLocal.ThreadLocalMap的内部类,然后ThreadLocal.ThreadLocalMap里面有一个Entry数组管理着这些存储的对象。
  2. 线程死亡时,线程局部变量会自动回收内存;
  3. 当线程拥有的局部变量超过了容量的2/3(没有扩大容量时是10个),会涉及到ThreadLocalMapEntry的回收;

参考链接: ThreadLocal 源码剖析

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档