[Java] Understand ThreadLocal

Source: Internet
Author: User

Someone in the group said yesterday that Struts2.x was used in other layers of non-Action.
ServletActionContext. getRequest ()
Q: Why can I get it successfully?

Why do you think it cannot be obtained?
In fact, it is easier to prove that there are rabbits in the forest than to prove that there are no rabbits in the forest-we just need to catch rabbits.

The source code is clear.
First, let's take a look at what ServletActionContext. getRequest () has done:

/**     * 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 () returns an ActionContext. The get (String key) of ActionContext is only get in Map:

/**    * 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);   }

In fact, the question is not get (), but ActionContext. getContext (). Read the comment that says Returns the ActionContext specific to the current thread:

/**    * 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();   }

The actionContext here is a ThreadLocal type:

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

It may be because you do not understand ThreadLocal--|

It's not LocalThread, it's ThreadLocal, What Is ThreadLocal?
Oh, you may remember.
It is the local variable of the thread.
We once declared a static ThreadLocal in a class <...> or something.
We once override his initialValue (), called his get () set () remove ().

ThreadLocal contains a static class ThreadLocalMap.
Taking set () as an example, when we call set, we actually store this ThreadLocal as the Key in Map.

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

You should be aware of how to obtain the Map, getMap (Thread. currentThread ()):

ThreadLocalMap getMap(Thread t) {    return t.threadLocals;}

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/122PJ513-0.jpg "title =" QQ20131127102413.jpg "alt =" 102655383.jpg"/>
All our ThreadLocal objects are in this 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) {// the source code is omitted}


To sum up, that's all:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/122PJ2S-1.jpg "title =" ThreadLocal.jpg "alt =" 182158973.jpg"/>



This article is from the "0xCAFEBABE" blog, please be sure to keep this source http://runtime.blog.51cto.com/7711135/1332231

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.