【Java】理解ThreadLocal

昨天群里有人说道使用Struts2.x时在非Action的其他层使用了ServletActionContext.getRequest()问:为什么能成功获取到?为什么会认为不能获取?事实上,证明森林中有兔子比证明森林中没有兔子简单——我们只需要抓到兔子。

这个问题看了源码自然明了首先看一下ServletActionContext.getRequest()做了些什么:

/*** Gets the HTTP servlet request object.** @return the HTTP servlet request object.*/public static HttpServletRequest getRequest() {return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);}

ActionContext.getContext()返回一个ActionContext,ActionContext的get(String key)只不过是在Map里get而已:

/*** Returns a value that is stored in the current ActionContext by doing a lookup using the value’s key.** @param key the key used to find the value.* @return the value that was found using the key or <tt>null</tt> if the key was not found.*/ public Object get(String key) {return context.get(key); }/*** Returns the ActionContext specific to the current thread.** @return the ActionContext for the current thread, is never <tt>null</tt>.*/ public static ActionContext getContext() {return actionContext.get(); }

此处的actionContext是一个ThreadLocal类型的:

static ThreadLocal<ActionContext> actionContext = new ThreadLocal<ActionContext>();

会有疑问可能是因为没有理解ThreadLocal – -||不是LocalThread,是ThreadLocal,,ThreadLocal是什么?哦,可能还记得。他是线程的局部变量。我们曾经在一个类里声明过一个static ThreadLocal<…> 什么的。我们曾经override过他的initialValue()、调用过他的get() set() remove()。ThreadLocal里有个static class ThreadLocalMap。以set()为例,我们调用set时实际上是将这个ThreadLocal作为Key存入了Map中。

public void set(T value) {Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t);if (map != null)map.set(this, value);elsecreateMap(t, value);}ThreadLocalMap getMap(Thread t) {return t.threadLocals;}

我们的ThreadLocal object都在这个map里面:

/** * Construct a new map initially containing (firstKey, firstValue). * ThreadLocalMaps are constructed lazily, so we only create * one when we have at least one entry to put in it. */ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {table = new Entry[INITIAL_CAPACITY];int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY – 1);table[i] = new Entry(firstKey, firstValue);size = 1;setThreshold(INITIAL_CAPACITY);}/** * Set the value associated with key. * * @param key the thread local object * @param value the value to be set */private void set(ThreadLocal key, Object value) {//源码略}

总结起来,仅此而已:

本文出自 “Iridescent” 博客,请务必保留此出处

带着我的相机和电脑,远离繁华,走向空旷。

【Java】理解ThreadLocal

相关文章:

你感兴趣的文章:

标签云: