ThreadLocal理解

ThreadLocal理解

一. ThreadLocal的get(),set()实现方式.

   public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

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


1.也就是说ThreadLocale.get()操作的map,key是当前线程,value是值。
2.此map是thread的一个成员属性,随着thread的回收而销毁。
3.如果这个thread放在线程池里,map是有内存溢出的风险,所以线程运行最后最好执行threadload.remove()。

二.lucene对ThreadLocale的扩展

org.apache.lucene.util.CloseableThreadLocal完全自己实现了一个ThreadLocale。
通过ThreadLocal<WeakReference<T>> t和Map<Thread,T> hardRefs实现。

public void set(T object) {

    t.set(new WeakReference<T>(object));

    synchronized(hardRefs) {
      hardRefs.put(Thread.currentThread(), object);
      maybePurge();
    }

}

public T get() {
    WeakReference<T> weakRef = t.get();
    if (weakRef == null) {
      T iv = initialValue();
      if (iv != null) {
        set(iv);
        return iv;
      } else {
        return null;
      }
    } else {
      maybePurge();
      return weakRef.get();
    }
}

  public void close() {
    // Clear the hard refs; then, the only remaining refs to
    // all values we were storing are weak (unless somewhere
    // else is still using them) and so GC may reclaim them:
    hardRefs = null;
    // Take care of the current thread right now; others will be
    // taken care of via the WeakReferences.
    if (t != null) {
      t.remove();
    }
    t = null;
  }



参考:
http://www.iteye.com/topic/103804
http://www.iteye.com/topic/1057974
http://www.iteye.com/topic/704710



你可能感兴趣的:(threadLocal)