To thoroughly understand the threadlocal, but also to see its source!
For threadlocal, the most common method we use is: Get ()/set (value)/remove () these 3 operations. So first look at the source code of the Set (value) method:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/7F/wKiom1TUYhXCB1viAAB-6--R7pE656.jpg "title=" Thread05.png "alt=" Wkiom1tuyhxcb1viaab-6--r7pe656.jpg "/>
Description At set time, the current thread is fetched, and a threadlocalmap is obtained through the current thread, and if so, the user-supplied value is set to Threadlocal as key.
Follow the Getmap (Thread) and Createmap (Thread,t) methods:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/80/wKioL1TVakbS7gUcAAAyeH9XK-I690.jpg "title=" Thread06.png "alt=" Wkiol1tvakbs7gucaaayeh9xk-i690.jpg "/>
Returns the member variable threadlocals of a thread, looking at the source code discovery for the following thread: Threadlocal.threadlocalmap threadlocals = null;
Threadlocalmap is the inner class defined in the Threadlocal class, but it is a member variable of thread!
In fact, we can come to the conclusion that:
To store something in a threadlocal variable is equivalent to keeping something in a map member variable of the current thread, key is the Threadlocal object, and value is what you want to put. In this case, it can be taken anywhere on a thread and is absolutely safe because it is a property of the thread itself and not shared by multiple threads.
You can look at Createmap (thread,t) To verify the above conclusions: void Createmap (Thread T, T firstvalue) {t.threadlocals = new Threadlocalmap (this, firstvalue); }
It is due to the characteristics of threadlocal, which makes it application in struts/spring!
When a request arrives at the Web container, in general, the Web container pulls out an idle thread from the thread pool, and how does the requested data, such as request, relate to this thread? STRUTS2 will encapsulate the requested data and put it into threadlocal, so the request data in one thread is absolutely safe!
And in spring, threadlocal is everywhere!
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/59/84/wKiom1TVcCPDX4CIAAC-IbgxKgU436.jpg "title=" Thread08.png "alt=" Wkiom1tvccpdx4ciaac-ibgxkgu436.jpg "/> In the DAO layer, we did not pass the connection to the DAO method explicitly, how did it get to connection? Why do we get the same connection in one thread of spring? ......
|