标签:.com dog 引用 question null new t 需要 ESS set
ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("jinshuai");
threadLocal.get();
public void set(T value) {
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
// 获取ThreadLocalMap
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
public T get() {
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取当前线程对应的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
// 将ThreadLocal(this)作为key获取entry
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
// 获取entry的value
T result = (T)e.value;
return result;
}
}
// 如果entry为空
return setInitialValue();
}
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
};
public String formatIt(Date date)
{
return formatter.get().format(date);
}
比如在Servlet中:
doGet(HttpServletRequest req, HttpServletResponse resp) {
User user = getLoggedInUser(req);
doSomething(user)
doSomethingElse(user)
renderResponse(resp,user)
}
每个方法都需要一个user,不够优雅(咳咳...),此时可以通过设置一个ThreadLocal单例,然后set(user):
doGet(HttpServletRequest req, HttpServletResponse resp) {
User user = getLoggedInUser(req);
ThreadLocalSingleInstace.getThreadLocal().set(user)
try {
doSomething()
doSomethingElse()
renderResponse(resp)
}
finally {
ThreadLocalSingleInstace.getThreadLocal().remove()
}
}
// 获取ThreadLocal单例
class ThreadLocalSingleInstace {
static private ThreadLocal threadLocal = new ThreadLocal<User>();
static ThreadLocal<User> getThreadLocal() {
return threadLocal;
}
}
// 会移除这个Entry
threadLocal.remove();
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
标签:.com dog 引用 question null new t 需要 ESS set
原文地址:https://www.cnblogs.com/jinshuai86/p/9270705.html