3.ThreadLocal源码

作者: 进击的小鹿 | 来源:发表于2016-11-03 14:55 被阅读13次

    ThreadLocal

    属于java.lang,提供线程局部变量,用来处理多线程并发的。

    使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本。
    因此每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

    机制:

    每个线程有一个自己的 ThreadLocalMap 对象
    每一个 ThreadLocal 对象有一个创建时生成唯一的 Id
    访问一个 ThreadLocal 变量的值,就是用这个唯一 Id 去 本线程 的 ThreadLocalMap 中查找对应的值

    **简单具体点说,ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本,由于Key值不可重复,每一个“线程对象”对应线程的“变量副本”,而到达了线程安全。
    **

    源码解析:

    package java.lang;
    import java.lang.ref.*;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class ThreadLocal<T> {
    
    private final int threadLocalHashCode = nextHashCode();
    
    //从0开始,原子更新下一个,
    private static AtomicInteger nextHashCode =
        new AtomicInteger();
    
    
    //hash code 从 0 开始不断累加 0x61c88647 生成的。0x61c88647,目的为了让 hash code 能更好地分布在尺寸为 2 的 N 次方的数组里
    private static final int HASH_INCREMENT = 0x61c88647;
    
    //返回下个HashCode
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }
    
    //返回当前线程初始值作为当前ThreadLocal变量,返回null
    protected T initialValue() {
        return null;
    }
    
    
    public ThreadLocal() {
    }
    
    
    //返回ThreadLocal变量在当前线程副本的值。如果该变量在当前线程中没有值,返回初始化的值。T泛型
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);//得到map的实体
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }
    
    //设置成初始值,并返回。
    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;
    }
    
    //设置成特定的值value
    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
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }
    
    //获取线程t的ThreadLocalMap;
    //在Thread类中有属性,也就是线程附属的一个ThreadLocalMap threadLocals: 
    //ThreadLocal.ThreadLocalMap threadLocals = null;
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals; 
    }
    
    //创建线程的threadLocals
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    
    //静态方法,创建继承于父线程的ThreadLocalMap
    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }
    
    //一种嵌入式的替代吧,在子类中已经重新定义。在这里定义是为了提供createInheritedMap的工厂方法而不需在InheritableThreadLocal再子类化map class。
    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }
    
     
    //内部类ThreadLocalMap,哈希map来维护线程局部变量。没有操作暴露在ThreadLocal类之外。
    //访问权限为package private 的内部类,因此可以在 Thread 类中引用(都是 java.lang 包下的)
    //哈希表实体用WeakReferences作为key,来维持大而长时间的使用。
    static class ThreadLocalMap {
    
        //泛型T 是 ThreadLocal
        static class Entry extends WeakReference<ThreadLocal> {
            /** The value associated with this ThreadLocal. */
            Object value;
    
            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }
    
           //初始容量,必须是2的幂
        private static final int INITIAL_CAPACITY = 16;
        
        private Entry[] table;
        
        private int size = 0;
    
       //要调整的阈
        private int threshold; // Default to 0
    
       //设置阈 最少 len * 2 / 3
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }
        
         // i自增 (模 len):加1操作,下一个索引
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }
    
       //i自减 (模 len):减1操作,上一个索引
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }
    
        //构造包含(firstKey, firstValue)的Map,懒惰构造,仅当至少有entry扔进的时候创建。
        ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
    
        //带参parentMap构造函数(与父线程有关),只允许createInheritedMap调用。
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new Entry[len];
    
            for (int j = 0; j < len; j++) {
                Entry e = parentTable[j];
                if (e != null) {
                    ThreadLocal key = e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }
    
        //返回该key关联的Entry。直接命中或者getEntryAfterMiss()
        private Entry getEntry(ThreadLocal key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }
    
        //未直接命中,便使用该方法找Entry。
        private Entry getEntryAfterMiss(ThreadLocal key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;
    
            while (e != null) {
                ThreadLocal k = e.get();
                if (k == key)
                    return e;
                if (k == null)
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }
    
           //设置该key关联的value。
        private void set(ThreadLocal key, Object value) {
    
            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();
        }
    
       //移除该key关联的Entry
        private void remove(ThreadLocal key) {
            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)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }
    
        //替换
        private void replaceStaleEntry(ThreadLocal key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;
    
             
            //往回找stale entry
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len))
                if (e.get() == null)
                    slotToExpunge = i;
    
            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal k = e.get();
    
                if (k == key) {
                    e.value = value;
    
                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;
    
                    // 如果前面存在stale entry ,那么从它开始删。
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);//clean
                    return;
                }
    
                if (k == null && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }
    
            // key没找到, 放new entry 在stale slot
            tab[staleSlot].value = null;
            tab[staleSlot] = new Entry(key, value);
    
            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);//clean
        }
    
        //通过重散列在staleSlot和下一个为空的slot之间的所有可能冲突的项目,删除stale entry。
        //这个操作其实删除了其他在后一个null之前的stale entries.
        //返回下一个为空的index
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
    
            // 清除staleSlot位置的entry,也就是置为null,size减1
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;
    
            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;
    
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }
    
        //remove,从i下一个开始,n是scan控制,log2(n)个cells被查询, 有stale entry情况。
        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;  // 有remove的就会返回true
        }
    
         
        //显示移除stale entries,如果size >= threshold - threshold / 4,则resize()
        private void rehash() {
            expungeStaleEntries();
    
            // Use lower threshold for doubling to avoid hysteresis(迟滞现象)
            if (size >= threshold - threshold / 4)
                resize();
        }
    
        //二倍扩容。
        private void resize() {
            Entry[] oldTab = table;
            int oldLen = oldTab.length;
            int newLen = oldLen * 2;
            Entry[] newTab = new Entry[newLen];
            int count = 0;
    
            for (int j = 0; j < oldLen; ++j) {
                Entry e = oldTab[j];
                if (e != null) {
                    ThreadLocal k = e.get();
                    if (k == null) {
                        e.value = null; // Help the GC
                    } else {
                        int h = k.threadLocalHashCode & (newLen - 1);
                        while (newTab[h] != null)
                            h = nextIndex(h, newLen);
                        newTab[h] = e;
                        count++;
                    }
                }
            }
    
            setThreshold(newLen);
            size = count;
            table = newTab;
        }
    
        //删除过期的entries:e.get() == null
        private void expungeStaleEntries() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }
    }
    }
    

    说明:
    1.0x61c88647:数学中的神秘数字,神奇至极啊

    This number represents the golden ratio (sqrt(5)-1) times two to the power of 31. The result is then a golden number, either 2654435769 or -1640531527.

    2.示例1:私有静态 ThreadLocal
    实例(serialNum
    )为调用该类的静态 SerialNum.get()
    方法的每个线程维护了一个“序列号”,该方法将返回当前线程的序列号。(线程的序列号是在第一次调用 SerialNum.get()
    时分配的,并在后续调用中不会更改。)

    public class ThreadLocalTest1 {
    
    private static int nextSerialNum = 0; //静态变量
    
    private static ThreadLocal serialNum = new ThreadLocal() {
        protected synchronized Object initialValue() {   // 同步方法
            return new Integer(nextSerialNum++); 
        }
    };
    
    public static int get() {
        return ((Integer) (serialNum.get())).intValue();
    }}
    

    3.示例2:在线程类内部创建ThreadLocal :线程 隔离

    (1)、在多线程的类(如ThreadDemo类)中,创建一个ThreadLocal对象threadXxx,用来保存线程间需要隔离处理的对象xxx。

    (2)、在ThreadDemo类中,创建一个获取要隔离访问的数据的方法getXxx(),在方法中判断,若ThreadLocal对象为null时候,应该new()一个隔离访问类型的对象,并强制转换为要应用的类型。

    (3)、在ThreadDemo类的run()方法中,通过调用getXxx()方法获取要操作的数据,这样可以保证每个线程对应一个数据对象,在任何时刻都操作的是这个对象。

    代码参考下面的第二个网址。

    4 示例 线程安全

    public class ConnectionManager {  
    
    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {  
        @Override  
        protected Connection initialValue() {  
            Connection conn = null;  
            try {  
                conn = DriverManager.getConnection(  
                        "jdbc:mysql://localhost:3306/test", "username",  
                        "password");  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
            return conn;  
        }  
    };  
    
    public static Connection getConnection() {  
        return connectionHolder.get();  
    }  
    
    public static void setConnection(Connection conn) {  
        connectionHolder.set(conn);  
    }  }  
    

    参考:

    http://www.tuicool.com/articles/2QjEzm
    http://blog.csdn.net/vking_wang/article/details/14225379

    相关文章

      网友评论

        本文标题:3.ThreadLocal源码

        本文链接:https://www.haomeiwen.com/subject/qkxjuttx.html