Threadlocal usage in Web Applications
1. What is threadlocal:
What is threadlocal? In fact, threadlocal is not a local implementation version of a thread, it is not a thread, but Thread Local variable (thread local variable ). It may be more appropriate to name it threadlocalvar. Threadlocal is a simple function. It provides a copy of the variable value for every thread that uses the variable. Each thread can change its own copy independently, it does not conflict with copies of other threads. From the thread perspective, it seems that every thread has the variable completely. Thread Local variables are not new in Java. In other language compilers (such as ibm xl Fortran), they provide direct support at the language level. Java does not provide direct support at the language level, but provides a threadlocal class to support it. Therefore, the code for compiling local variables of threads in Java is relatively clumsy, this may be one of the reasons why local variables of threads are not widely used in Java.
2. threadlocal has an important feature in reality:
Each HTTP request is an independent thread with an independent threadlocal. With this feature, we can use threadlocal for temporary access values in the HTTP request lifecycle, and pass values between different classes. For example, transferring database connections. So far, we can use the following methods to store values without scope variables in Web applications:
Request, threadlocal, session, application, etc. The scope is well known and will not be described in detail here. The difference between request and threadlocal is described.
3. Difference between request and threadlocal:
1) The access value is different.
The request can store multiple values based on the key access value and one request.
Threadlocal can only store one value. The get and set methods of threadlocal do not have a parameter key.
2) The usage is different.
Request is used in the presentation layer, generally in action and servlet.
Threadlocal can be used anywhere. It is generally used in many framework base classes, such as storing the current database connection.