苍穹外卖 ThreadLocal 用户上下文

苍穹外卖 ThreadLocal 用户上下文

1 使用

  • 可以把ThreadLocal看成一个全局Map<Thread, Object>:每个线程获取ThreadLocal变量时,总是使用Thread自身作为key, 一个线程上的函数获取到的都是同一个 Object
package com.sky.context;  

public class BaseContext {  

    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();  

    public static void setCurrentId(Long id) {  
        threadLocal.set(id);  
    }  

    public static Long getCurrentId() {  
        return threadLocal.get();  
    }  

    public static void removeCurrentId() {  
        threadLocal.remove();  
    }  

}

1.1 及时remove

try {
    threadLocalUser.set(user);
    ...
} finally {
    threadLocalUser.remove();
}