ThreadLocal的get方法
public T get() {
Thread t = Thread.currentThread(); //取到当前线程
ThreadLocalMap map = getMap(t); //取到线程t中map<Thread,Object>
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
当我们调用ThreadLoacl的get方法时,首先取得当前线程(即调用get方法的线程),然后取到当前线程中的map,我们看源码可以看到Thread类中有这个成员变量:ThreadLocal.ThreadLocalMap threadLocals = null;
然后从map中以当前线程t取到value。
set()方法也是一样,取到当前线程,然后取到当前线程中的map,再已当前线程为key存入自己要存的值。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
用例:一般的web应用中,我们需要知道登录用户的信息,一般我们是将用户信息放在session中(session.setAttribute("key","value"))。在程序中可以通过request.getSession.getAttribute("key")取到用户信息。但是如果我们想在一个manage业务层中取得用户信息,就必须将request传入manange的方法中,这样是不好的,也是不方便的。
当浏览器发送一个请求到服务器时,服务器会新启一个线程处理这个请求,所以我们可以在请求到来时,取到session中的用户信息,再将它放入ThreadLocal中。那么我们就可以在当前线程的任何地方通过Threadlocal取到我们需要的用户信息。
public abstract class SnsLoginContextHolder {
private final static ThreadLocal<SnsLoginContext> holder = new ThreadLocal<SnsLoginContext>();
/**
* 取得loginContext
* @return LoginContext
*/
public static final SnsLoginContext getLoginContext(){
SnsLoginContext loginContext = holder.get();
if (loginContext == null){
loginContext = new SnsLoginContext();
holder.set(loginContext);
}
return loginContext;
}
/**
* 清除loginContext
*/
public static final void clearLoginContext(){
holder.remove();
}
}
public T get() {
Thread t = Thread.currentThread(); //取到当前线程
ThreadLocalMap map = getMap(t); //取到线程t中map<Thread,Object>
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
当我们调用ThreadLoacl的get方法时,首先取得当前线程(即调用get方法的线程),然后取到当前线程中的map,我们看源码可以看到Thread类中有这个成员变量:ThreadLocal.ThreadLocalMap threadLocals = null;
然后从map中以当前线程t取到value。
set()方法也是一样,取到当前线程,然后取到当前线程中的map,再已当前线程为key存入自己要存的值。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
用例:一般的web应用中,我们需要知道登录用户的信息,一般我们是将用户信息放在session中(session.setAttribute("key","value"))。在程序中可以通过request.getSession.getAttribute("key")取到用户信息。但是如果我们想在一个manage业务层中取得用户信息,就必须将request传入manange的方法中,这样是不好的,也是不方便的。
当浏览器发送一个请求到服务器时,服务器会新启一个线程处理这个请求,所以我们可以在请求到来时,取到session中的用户信息,再将它放入ThreadLocal中。那么我们就可以在当前线程的任何地方通过Threadlocal取到我们需要的用户信息。
public abstract class SnsLoginContextHolder {
private final static ThreadLocal<SnsLoginContext> holder = new ThreadLocal<SnsLoginContext>();
/**
* 取得loginContext
* @return LoginContext
*/
public static final SnsLoginContext getLoginContext(){
SnsLoginContext loginContext = holder.get();
if (loginContext == null){
loginContext = new SnsLoginContext();
holder.set(loginContext);
}
return loginContext;
}
/**
* 清除loginContext
*/
public static final void clearLoginContext(){
holder.remove();
}
}