MATERIALS:
Http://www.javaeye.com/topic/103804
Http://www.javaeye.com/topic/617368
Core content:
In short, threadlocal is not used to solve the problem of shared object access, but mainly provides methods to keep objects and convenient object access methods to avoid passing parameters. Two points are summarized:
1. Each thread has its own threadlocalmap class object, which can keep the thread's own objects in it. The thread can correctly access its own objects in various tubes.
2. Use a shared threadlocal static instance as the key, save the references of different objects to threadlocalmap of different threads, and then run get () of the static threadlocal instance everywhere () method to get the object saved by the thread, avoiding the trouble of passing this object as a parameter.
Threadlocal is not used to solve the problem of shared object access, but to process a service in a multi-threaded environment. When a method needs to recursively depend on other methods, however, we need to share parameters in these methods. For example, if method A () is available, Method B () is called in this method, and method C () is called in Method B, that is, a --> B ---> C, if user objects are required for A, B, and C, A (User user) --> B (User user) --- C (User user) is a common practice ). However, if threadlocal is used, we can use another solution:
- Define a static threadlocal object in an interface, for example, public static threadlocal = new threadlocal ();
- Then let the class where A, B, and C methods are located assume that Class A, Class B, and class C all implement interfaces in 1.
- When calling a, use a. threadlocal. Set (User) to put the user object into the threadlocal environment.
- In this way, we can use the threadlocal. Get () method in the method body to obtain the user object without passing parameters in method A, Method B, and method C.
The above class A, Class B, and class C correspond to the web layer action when we were doing Web Development ---> service at the business logic layer --> Dao at the data access layer, when we want to share parameters in these three layers, we can use threadlocal.