手写 ThreadLocal

    技术2024-12-22  15

    这是一个简易版的 ThreadLocal,实现了 ThreadLocal 的 set,get,及 remove 方法。

    package per.lvjc.concurrent.threadlocal; import java.util.HashMap; import java.util.Map; public class LvjcThreadLocal<T> { private Map<Thread, Map<LvjcThreadLocal, Object>> mapMap; private T initValue; public LvjcThreadLocal() { this.mapMap = new HashMap<>(); } public LvjcThreadLocal(T initValue) { this.mapMap = new HashMap<>(); this.initValue = initValue; } public void set(T value) { Thread thread = Thread.currentThread(); Map<LvjcThreadLocal, Object> currentThreadMap = mapMap.get(thread); if (currentThreadMap == null) { currentThreadMap = new HashMap<>(); mapMap.put(thread, currentThreadMap); } currentThreadMap.put(this, value); } public T get() { Thread thread = Thread.currentThread(); Map<LvjcThreadLocal, Object> currentThreadMap = mapMap.get(thread); if (currentThreadMap == null) { return initValue; } return (T) currentThreadMap.get(this); } public void remove() { Thread thread = Thread.currentThread(); Map<LvjcThreadLocal, Object> currentThreadMap = mapMap.get(thread); if (currentThreadMap != null) { currentThreadMap.remove(this); } } }

    就这样,没了。

    set,get 的基本功能有了,还可以通过带初始值的构造方法来设置初始值,可以当做 JDK ThreadLocal 一样来用。

    基本原理与 JDK ThreadLocal 一致。

    如果把里面的那层 Map 替换成 ThreadLocal.ThreadLocalMap,即变成 Map<Thread, ThreadLocalMap>;

    再把 ThreadLocalMap 放到 Thread 对象里面去,而不是全都放在一个 ThreadLocal 对象里面以 Thread 做映射,就变成 JDK ThreadLocal 了。

    Processed: 0.013, SQL: 9