public class MyThreadLocal<T> {
Map<Thread,T> container = Collections.synchronizedMap(new HashMap<Thread, T>());
public T get(){
Thread t = Thread.currentThread();
T value = container.get(t);
if(null == value&& !container.containsKey(t)){
value = initialValue();
container.put(t,value);
}
return value;
}
public void set(T value){
container.put(Thread.currentThread(),value);
}
public void remove(){
container.remove(Thread.currentThread());
}
protected T initialValue(){
return null;
}
}
评论加载中