ThreadLocal

ThreadLocal

ThreadLcoal的使用

线程并发 : 在多线程并发的场景下

传递数据 :我们可以通过ThreadLocal在同一线程中,不同组件中传递公共变量

线程隔离 :每个线程变量都是独立的,不会相互影响

一般用于关联线程和线程的上下文,我们通过ThreadLcoal获取到这个数据之后,在这个线程的生命周期中我们的ThreadLocal起作用,而不会获取到在线程并发的时候获取到的变量

package ThreadLocal;

class Book{

    ThreadLocal<Integer> numbers = new ThreadLocal<>();

    public Book(int num) {
        numbers.set(100);
    }

    public int getNum() {
        return numbers.get();
    }

    public void setNumbers(int numbers) {
        this.numbers.set(numbers);
    }

    public void removeNumbers() {
        this.numbers.remove();
    }
}


public class Demo1 {

    public static void main(String[] args) {
        Book b = new Book(50);
        Thread t1 = new Thread(() -> {
            System.out.println(b.numbers.get() + "" + Thread.currentThread().getName());
            b.numbers.set(100);
            System.out.println(b.numbers.get() + "" + Thread.currentThread().getName());
            b.numbers.remove();
        },"A");

        Thread t2 = new Thread(() -> {
            System.out.println(b.numbers.get() + "" + Thread.currentThread().getName());
            b.numbers.set(200);
            System.out.println(b.numbers.get() + "" + Thread.currentThread().getName());
            b.numbers.remove();
        },"B");

        t1.start();
        t2.start();
    }

}

引入ThreadLocal的原因(与synchronized的区别)
  1. ThreadLocal和synchronized都是处理多线程并发访问量的问题

synchronized 同步机制,对这个访问量进行加锁操作,同一个时间点,只能有一个线程对这个数据进行访问,让不同的线程排队等待访问这个变量,如果我们需要对数据进行增删改,一般使用synchronized。

ThreadLocal让多个线程都可以同时访问这个变量,在线程的内部创建一个ThreadLocalMap,产生了一个副本变量,我们不会这个副本变量去改变我们内存中的变量,我们只是需要这个ThreadLcoal,并且我们要保证我们在线程并发的时候不会得到别的线程的数据,就需要使用ThreadLocal,保持在内部的一致性。

ThreadLocal一般更适合我们的高并发,并且不去修改内存中的变量。

ThreadLocal方案的好处:

  1. 传递数据 : 保存每个线程绑定的数据,在需要的地方可以直接获取,避免参数直接传递带来的代码耦合的问题
  2. 线程隔离:各线程之间的数据相互隔离又具有并发性,避免同步带来的性能损失
ThreadLocal的内部结构

当我们在一个线程内创建一个ThreadLocal的时候,我们就会创建一个ThreadLocalMap,这个map中的key值未ThreadLocal本事,value为我们保存的Object对象

具体过程:

  1. 每个Thread线程内部都有一个Map(ThreadLocalMap)
  2. Map里面存储的ThreadLocal对象(key)和线程的变量副本(value)
  3. Thread内部Map由ThreadLocal维护,ThreadLocal负责向map获取和设置变量值
  4. 对于不同的线程,每次获取副本值的时候,别的线程并不能获取到当前线程的副本值,形成了副本值,互不干扰

ThreadLocalMap并未实现Map接口,而是在自己的内部实现了一个map,而使用处理冲突的方法并不是拉链发,而是线性探测法。

Thread的结束的时候,我们Thread维护的ThreadLocalMap随之销毁

ThreadLocalMap源码分析
static class ThreadLocalMap {
        // 继承弱引用
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;
            // Entry对象
            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
        // 初始容量
        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;
        }

        
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

       
        // ThreadLocalMap的构造方法
        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);
        }

        // 
        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) {
                    @SuppressWarnings("unchecked")
                    ThreadLocal<Object> key = (ThreadLocal<Object>) 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++;
                    }
                }
            }
        }

        // 获取我们的Entry对象 根据ThreadLocal的key
        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
                // 找到不到key的时候 直接找到它的hash槽 
                // 也就是我们根据的线性探测法而放入的对象
                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;
        }

        // 设置对应的Entry对象,如果存在则改变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) {
                    // k == null的时候
                    // 证明没有key(弱引用的时候被消除)设置了key value
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

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

        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;

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

      
        // 删除一些过时的条目 也就是我们过时Entry对象
        // ThreadLcoal对象是弱引用
        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;
        }

        // 寻找一些过时的条目 并且删除掉
        // 添加一个新条目的时候,我们再去看看 
        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;
        }

        // 是否决定扩容
        private void rehash() {
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            // 如果hash因子过大就扩容
            if (size >= threshold - threshold / 4)
                resize();
        }

        /**
         * Double the capacity of the table.
         */
       // 扩容
        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;
        }

        /**
         * Expunge all stale entries in the table.
         */
        // 删除掉过时的Entry对象
        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);
            }
        }
    }
ThreadLocal源码分分析
属性
private final int threadLocalHashCode = nextHashCode();

private static AtomicInteger nextHashCode =
    new AtomicInteger();

private static final int HASH_INCREMENT = 0x61c88647;
构造方法和简单方法
 	private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }
	
	protected T initialValue() {
       	return null;
    }
   	 
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }
    
    public ThreadLocal() {
    }
Set方法
 public void set(T value) {
        // 获取当前线程
     Thread t = Thread.currentThread();
     // 获取ThreadLcoalMap 根据我们当前线程
     ThreadLocalMap map = getMap(t);
     if (map != null)
         // 设置值
         map.set(this, value);
     else
         // 创建map
         createMap(t, value);
    }

   void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

Get方法
	 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            // 获取map中的Entry对象
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        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为 null
   protected T initialValue() {
        return null;
    }

Remove方法
	public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
	}

ThreadLoaclMap和内存泄露

在这里插入图片描述

  1. 在栈中都存在着我们ThreadLocal和CurrentThread的引用。
  2. 当我门这个ThreadLocalRef被销毁的时候,也就是说我们关联我们ThreadLocal对象的左边的强引用的对象被销毁,根据可达性分析,在执行GC的时候弱引用被断开,我们清楚了ThreadLocal所占用的空间,但是我们Entry对象还存在虽然 key == null,但key存在,并且value也存在,并且引用着我们Object对象,也就是说我们没有销毁这个Entry对象的时候,即使这个ThreadlLcoal对象已经销毁,但是这个Entry对象依旧占用空间,因为我们Thread下的ThreadLocalMap还指向我们的Entry对象,只要还有这个强引用存在,就会去占用我们空间,从而导致我们的内存泄露。
  3. 也就是说只要我们没有手动删除这个Entry对象 并且Thread依旧存活,这个Entry对象就会一直存在。只要没有手动删除,这个Entry对象存活周期就和我们Thread的生命周期一样长。从而造成内存泄露。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值