ThreadLocal源碼分析

ThreadLocal源碼分析

threadlocal是一個線程內部的數據存儲類。某線程儲存的數據,只有這個線程中才能獲取到存儲的數據。而其他線程是無法獲取到這個數據的。

一、ThreadLocal的使用

    private ThreadLocal<Integer> mThreadLocal = new ThreadLocal<Integer>();
    /***創建一個泛型爲String類型的ThreadLocal**/
    private ThreadLocal<String> mStringThreadLocal = new ThreadLocal<String>();

                
    new Thread("thread#1"){
                    @Override
                    public void run() {
                        Log.i(TAG, "run: [Therad#1]mThreadLocal"  );
                        mThreadLocal.set(10);
                        Log.i(TAG, "run: [Therad#1]mThreadLocal=" + mThreadLocal.get() );
                        /**爲mStringThreadLocal設置值***/
                        mStringThreadLocal.set("string10");
                        Log.i(TAG, "run: [Therad#1]mStringThreadLocal=" + mStringThreadLocal.get() );

                    }
                }.start();

                new Thread("thread#2"){
                    @Override
                    public void run() {
                        mThreadLocal.set(400);
                        Log.i(TAG, "run: [Therad#2]mThreadLocal=" + mThreadLocal.get() );
                        mStringThreadLocal.set("string400");
                        Log.i(TAG, "run: [Therad#2]mStringThreadLocal=" + mStringThreadLocal.get() );
                    }
                }.start();

二、存儲值

1、存儲值

    public void set(T value) {
        Thread t = Thread.currentThread();/***獲取當前線程**/
        ThreadLocalMap map = getMap(t);/**根據線程獲取線程的成員變量ThreadLocalMap,它是一種Map映射結構***/
        if (map != null)  
            map.set(this, value);
        else/**首次一般map爲空,需要爲thread t創建一個ThreadLocalMap**/
            createMap(t, value);
    }

2、獲取線程的ThreadLocalMap

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

3、首次存儲值,要創建一個LocalThreadMap複製給當前線程。

    void createMap(Thread t, T firstValue) { /**爲thread t創建一個ThreadLocalMap**/
        t.threadLocals = new ThreadLocalMap(this, firstValue);/**並且首個鍵值對key-value:key爲當前的ThreadLocal(比如mBooleanThread,mStringThread),values爲firstValue**/
    }

     非首次存儲值,直接存儲就行了

        if (map != null)  
            map.set(this, value);

4、創建構造LocalThreadMap中會創建一個Entry結構類型數組表table  ,

     將根據首個要存儲的數據:當前ThreadLocal和Value創建生成一個Entry對象,

      並放入table表中第i個位置(i的值是有當前的ThreadLocal中threadLocalHashCode值間接得到的)

   ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { /**首個鍵值對key-value:key爲當前的ThreadLocal(比如mBooleanThread,mStringThread),values爲firstValue**/
            table = new Entry[INITIAL_CAPACITY];/***創建一個Entry[]數組表**/
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);/**首頁key-value組裝成一個Entry,放在table中的第i個位置**/
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

看看Entry的具體數據結構

       static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

ThreadLocal的具體數據結構

 static class ThreadLocalMap {

        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;

        /**
         * The number of entries in the table.
         */
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0
 }

三、取值

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);/**拿到當前線程的ThreadLocalMap**/
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);/***根據當前的mThreadLocal獲取TheadMap**/
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;/***從Entry中取出value即可**/
                return result;
            }
        }
        return setInitialValue();
    }

1、根據當前線程獲取到線程對應的ThreadLocalMap

然後根據當前的ThreadLocal從ThreadLocalMap中獲取Entry()

        private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);//根據ThreadLocal中的hashcode做爲索引去線程中ThreadLocalMap的table數組表中拿到Entry,然後從Entry
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }

2、直接返回值即可

            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;/***從Entry中取出value即可**/
                return result;
            }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章