ThreadLocal 解析

ThreadLocal 类用来提供线程内部的局部变量,类似于方法中的局部变量。这种变量在多线程环境下访问(通过 get 或 set 方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量。ThreadLocal 实例通常来说都是 private static 类型的,用于关联线程和线程的上下文。

ThreadLocal 的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。

ThreadLocal 的使用

如何构造 ThreadLocal 实例
方法一:

@Test
    public void test3() {
        ThreadLocal<Long> threadLocal = new ThreadLocal<Long>(){
            @Override
            protected Long initialValue() {
                return System.currentTimeMillis();
            }
        };
    }

方法二:JDK 1.8 引入的函数式接口

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
                                                                  
    private final Supplier<? extends T> supplier;                 
                                                                  
    SuppliedThreadLocal(Supplier<? extends T> supplier) {         
        this.supplier = Objects.requireNonNull(supplier);         
    }                                                             
                                                                  
    @Override                                                     
    protected T initialValue() {                                  
        return supplier.get();                                    
    }                                                             
}                                                                 
ThreadLocal<Long> threadLocal = ThreadLocal.withInitial(System::currentTimeMillis);
System.out.println(threadLocal.get());
protected T initialValue() {   
    return null;               
}                        

返回当前线程的 ThreadLocal 的“初始值”。
这个方法将在一个线程第一次使用get方法访问变量时调用,除非线程先前调用了set方法,在这种情况下,不会为线程调用initialValue方法。
通常情况下,每个线程最多调用一次此方法,但在get()后调用remove(),可能会再次调用此方法。
这个实现只是返回null; 如果程序员希望线程局部变量具有非null的初始值,则必须对ThreadLocal进行子类化,并重写此方法。通常,将使用匿名内部类。

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();                             
}                                                         
  1. 首先获取当前线程
  2. 根据当前线程获取一个 ThreadLocalMap
  3. 如果获取的 ThreadLocalMap 不为空,则在 ThreadLocalMap 中以 ThreadLocal 的引用作为 key 来在 ThreadLocalMap 中获取对应的值,否则转到 5
  4. 如果 e 不为 null,则返回 e.value,否则转到 5
  5. map 为空或者 e 为空,则通过 initialValue 函数获取初始值 value,然后用ThreadLocal 的引用和 该value 作为 Key/Value 创建一个新的 ThreadLocalMap

Thread 中 保存有该 ThreadLocalMap

ThreadLocal.ThreadLocalMap threadLocals = null;

每一个 Thread 维护一个 ThreadLocalMap 映射表,这个映射表的 key 是 ThreadLocal 实例的引用,value 是真正需要存储的 Object。

ThreadLocalMap 解析

https://zhuanlan.zhihu.com/p/34406557
https://www.jianshu.com/p/dde92ec37bd1
https://www.jianshu.com/p/30ee77732843
https://blog.csdn.net/z_chenchen/article/details/88915901
https://zhuanlan.zhihu.com/p/40515974

ThreadLocal 使用

模拟记录方法调用的时间

class Profiler {
    private static final ThreadLocal<Long> TIME_THREAD_LOCAL = ThreadLocal.withInitial(System::currentTimeMillis);

    public static void begin() {
        TIME_THREAD_LOCAL.set(System.currentTimeMillis());
    }

    public static long end() {
        return System.currentTimeMillis() - TIME_THREAD_LOCAL.get();
    }
}

public class T {
	@Test
    public void test() {
        Profiler.begin();
        try {
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Profiler.end());
    }
}

比如在一个 web 应用中,我需要保存登陆用户的信息。就可以保存在 ThreadLocal 中。

public class UserTokenThreadLocal {
    private static ThreadLocal<UserLoginModel> contents = new ThreadLocal<>();
    public static void set(UserLoginModel userLoginModel) {
        contents.set(userLoginModel);
    }
    public static UserLoginModel get() {
        return contents.get();
    }
    public static void clear() {
        contents.remove();
    }
}

ThreadLocal 与 SpringMVC 的拦截器配合的天衣无缝。
比如,在 Controller 中的一些方法需要用户登陆才能执行。
在 Controller 处理前,将用户登陆的信息存放在 ThreadLocal 中。每次次请求/响应对应一个线程,所以与每个线程绑定的 ThreadLocal 也是唯一的,其他的线程无法访问。

public class UserTokenAuthInterceptor implements HandlerInterceptorAdapter {
    private final UserInfoService userInfoService;

    @Autowired
    public UserTokenAuthInterceptor(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        try {
            String token = req.getHeader("token");
            if (StringUtils.isBlank(token)) {
                token = req.getParameter("token");
                if (StringUtils.isBlank(token)) {
                    return write(res, false);
                }
            }
            UserModel userModel = userInfoService.getUserInfoByToken(token);
            if (userModel == null || userModel.getId() == 0) {
                return write(res, false);
            }
            UserTokenThreadLocal.set(new UserLoginModel(userModel.getId(), token, userModel.getMobile(), userModel.getUsername(), userModel.getAvatarUrl()));
            return true;
        } catch (Exception e) {
            //
        }
        return write(res, false);
    }

    private boolean write(HttpServletResponse res, boolean apiLogin) throws IOException {
        if (!apiLogin) {
            res.setContentType("application/json;charset=UTF-8");
            Writer writer = res.getWriter();
            writer.write(JSON.toJSONString(ApiResult.newResult(ServerCode.NO_LOGIN)));
        }
        return apiLogin;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object arg2, Exception arg3) throws Exception {
        UserTokenThreadLocal.clear();
    }
}

SpringMVC 中的应用:
在这里插入图片描述

在这里插入图片描述

package com.sankuai.inf.leaf;

import java.lang.ref.*;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/**
 * 脏结点 -> Entry::ThreadLocalMap key 为 null
 */
public class ThreadLocal<T> {
    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() {
    }

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

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

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

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

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

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

    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }

    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }

    static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedThreadLocal(Supplier<? extends T> supplier) {
            this.supplier = Objects.requireNonNull(supplier);
        }

        @Override
        protected T initialValue() {
            return supplier.get();
        }
    }

    static class ThreadLocalMap {
        static class Entry extends WeakReference<ThreadLocal<?>> {
            Object value;

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

        /**
         * table 默认初始大小
         */
        private static final int INITIAL_CAPACITY = 16;

        private Entry[] table;

        /**
         * table 元素个数
         */
        private int size = 0;

        /**
         * table 进行 resize 的阈值
         */
        private int threshold; // Default to 0

        /**
         * 设置 table 进行 resize 的阈值
         *
         * @param len
         */
        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(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);
        }

        /**
         * Construct a new map including all Inheritable ThreadLocals
         * from given parent map. Called only by createInheritedMap.
         *
         * @param parentMap the map associated with parent thread.
         */
        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++;
                    }
                }
            }
        }

        /**
         * Get the entry associated with key.  This method
         * itself handles only the fast path: a direct hit of existing
         * key. It otherwise relays to getEntryAfterMiss.  This is
         * designed to maximize performance for direct hits, in part
         * by making this method readily inlinable.
         *
         * @param key the thread local object
         * @return the entry associated with key, or null if no such
         */
        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);
        }

        /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         *
         * @param key the thread local object
         * @param i   the table index for key's hash code
         * @param e   the entry at table[i]
         * @return the entry associated with key, or null if no such
         */
        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;
        }

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

                // 发生 GC 时,ThreadLocal 弱引用被回收
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            // table 数组中不存在该 ThreadLocal
            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

        /**
         * Remove the entry for key.
         */
        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;
                }
            }
        }


        /**
         * 将数组元素空结点填充
         *
         * @param key
         * @param value
         * @param staleSlot
         */
        private void replaceStaleEntry(ThreadLocal<?> key, Object value, int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;

            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();

                // 取 staleSlot 后面的元素填充 staleSlot 空结点
                if (k == key) {
                    e.value = value;

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

                    // staleSlot 之前没有空结点
                    // slotToExpunge 表示要清除的结点
                    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;
            }

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

        /**
         * 清除 staleSlot 结点,将 staleSlot 后的结点提前
         *
         * @param staleSlot
         * @return staleSlot 后第一个空结点坐标
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // 清除 staleSlot 结点
            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;
        }

        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();
            if (size >= threshold - threshold / 4) {
                // 扩容
                resize();
            }
        }

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

        /**
         * 删除所有脏结点
         */
        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);
            }
        }
    }
}

test

package com.sankuai.inf.leaf;

import org.junit.Test;
import org.perf4j.StopWatch;
import org.perf4j.slf4j.Slf4JStopWatch;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liguanghui02
 * @date 2021/7/13
 */
public class T {
    @Test
    public void test1() {
        StopWatch sw = new Slf4JStopWatch();


        try {
            TimeUnit.MILLISECONDS.sleep(1024);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(sw.stop());
    }

    @Test
    public void test2() throws NoSuchFieldException, IllegalAccessException {
        ThreadLocal<String> threadLocal1 = ThreadLocal.withInitial(() -> "111");
        ThreadLocal<String> threadLocal2 = ThreadLocal.withInitial(() -> "222");
        ThreadLocal<String> threadLocal3 = ThreadLocal.withInitial(() -> "333");

        System.out.println(threadLocal1.get());
        System.out.println(threadLocal2.get());
        System.out.println(threadLocal3.get());

        Thread thread = Thread.currentThread();

        Field threadLocals = Thread.class.getDeclaredField("threadLocals");
        threadLocals.setAccessible(true);
        Object o = threadLocals.get(thread);
        System.out.println(o);
    }

    @Test
    public void test3() {
        AtomicInteger nextHashCode = new AtomicInteger();
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
        System.out.println(nextHashCode.getAndAdd(0x61c88647));
    }
}

内存泄漏问题
https://www.jianshu.com/p/1342a879f523

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值