ThreadLocal中有四个常用方法:

  1. initalValue
  2. set
  3. get
  4. remove

initalValue

先看initalValue,这个方法有两个调用方式

  1. 覆写initalValue
    /**
     * Returns the current thread's "initial value" for this
     * thread-local variable.  This method will be invoked the first
     * time a thread accesses the variable with the {@link #get}
     * method, unless the thread previously invoked the {@link #set}
     * method, in which case the {@code initialValue} method will not
     * be invoked for the thread.  Normally, this method is invoked at
     * most once per thread, but it may be invoked again in case of
     * subsequent invocations of {@link #remove} followed by {@link #get}.
     *
     * <p>This implementation simply returns {@code null}; if the
     * programmer desires thread-local variables to have an initial
     * value other than {@code null}, {@code ThreadLocal} must be
     * subclassed, and this method overridden.  Typically, an
     * anonymous inner class will be used.
     *
     * @return the initial value for this thread-local
     */
    protected T initialValue() {
        return null;
    }

注释说明,该方法在第一次调用 get 时触发。

  1. withInitial
    /**
     * Creates a thread local variable. The initial value of the variable is
     * determined by invoking the {@code get} method on the {@code Supplier}.
     *
     * @param <S> the type of the thread local's value
     * @param supplier the supplier to be used to determine the initial value
     * @return a new thread local variable
     * @throws NullPointerException if the specified supplier is null
     * @since 1.8
     */
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

调用withInitial 需要传入 实现 Supplier<? extends S> 对象,实际上就是需要一个get方法返回需要持有的对象。

再看get方法

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread(); // 获取当前线程
        ThreadLocalMap map = getMap(t); // 当前线程为 key 在 hashMap 中获取对应的 ThreadLocalMap
        if (map != null) { // 如果存在 就去取值
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) { // 值存在 就转换类型后返回
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        } 
        return setInitialValue(); // 不存在map 就去初始化
    }

注释说,返回当前线程在本地线程变量中的拷贝。如果当前线程获取不到变量,就调用 initialValue 方法,返回该方法的返回值。

看一下getMap(t) 及其相关的方法

/**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
  1. getMap:获取和一个ThreadLocal有关的map。
  2. createMap:创建一个ThreadLoacl有关的map,入参为 new ThreadLocalMap(this, firstValue), this 为当前的ThreadLocal对象;从这里可知 一个线程 thread 对应一个 threadLoacl 对象,一个threadLoacl 对象对应一个 map。
  3. threadLocals 与 当前线程有关的 ThreadLocal 值。

set

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread(); // 获取当前线程
        ThreadLocalMap map = getMap(t); // 获取map
        if (map != null)
            map.set(this, value); // 设置值
        else
            createMap(t, value); // 初始化map
    }

remove

/**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread()); // 获取map
         if (m != null)
             m.remove(this); // 删除map中对应的Threadlocal对象和其对应的值,this即当前调用该方法的 threadlocal 对象
     }

Fox_Valentin
1 声望1 粉丝