The use of threadlocal in Web applications
1, threadlocal is what:
What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread, it's not a threads, it's thread local variable. Perhaps it would be more appropriate to name it Threadlocalvar. A thread-local variable (ThreadLocal) is very simple in that it provides a copy of the variable value for each thread that uses the variable, and each thread can independently alter its own copy without conflict with the replica of the other thread. From a thread's point of view, it's as if every thread owns the variable entirely. Thread-local variables are not a new Java invention, and in other language compiler implementations (such as IBM XL FORTRAN), it provides direct support at the language level. Because Java does not provide direct support at the language level, but rather provides a threadlocal class to support, the code to write thread-local variables in Java is relatively clumsy, perhaps one reason why thread-local variables are not well popularized in Java.
2, threadlocal in the reality has an important feature:
Each HTTP request, is a separate thread, has an independent threadlocal. Using this feature we can use the Threadlocal, the HTTP request life cycle of the temporary access value, different classes for the transfer value. such as the transfer of database connections. So far we can use the following methods in Web applications where there are no scope variables to store values:
Request, ThreadLocal, session, application and so on. The scope is known, and is not explained in detail here. Now explain the difference between request and threadlocal.
3, request and threadlocal difference:
1), Access value mode is different.
Request can save multiple values based on key access value and one request.
Threadlocal can only save one value, Threadlocal get and set methods have no parameter key.
2), the use of different places.
Request is used in the presentation layer, generally in the action and servlet.
Threadlocal can be used anywhere, generally in the framework base class more, such as the current database connection.