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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值