JAVA ThreadLocal Object Servletactioncontext

Source: Internet
Author: User

Recently, during the development process, the ThreadLocal object was used to cache the data when a dictionary item service was made. There are some problems in using the ThreadLocal process, here and you share.

One What is ThreadLocal?

As the name implies, it is local variable (thread local variable). Its very simple function is to provide a copy of the variable value for each thread that uses the variable. From a thread's point of view, it's as if every thread has exactly the variable.

It consists of four methods consisting mainly of InitialValue(), Get (), set (T), remove (), where the initialvalue() method is a protected method, only in the overridden It's useful when ThreadLocal.

void Set (T): A current thread variable is stored for the thread that invokes the method.

T get (): Returns the value that this thread has stored in ThreadLocal , without returning null.

void Remove (): Removes the value that this thread has stored in ThreadLocal .

T initialvalue(): Used to generate an initial value when null,ThreadLocal returns a null value directly.

second, the principle of ThreadLocal

After viewing the Java source code,ThreadLocal to store "thread local variables" by using an instance of Threadlocalmap (note: Map non-java.util.Map subclass here), and when the value is set for the first time, if the map is empty, Creates a map and sets the value, but the map of the stored value is not a member variable of the ThreadLocal , but a member variable of the Java.lang.Thread class. ThreadLocal 's Set,get method source code is as follows:

   public void Set (T value) {        Thread T = Thread.CurrentThread ();        Threadlocalmap map = getmap (t);        if (map! = null)            Map.set (this, value);        else            createmap (t, value);}    Public T get () {        Thread T = Thread.CurrentThread ();        Threadlocalmap map = getmap (t);        if (map! = null) {            Threadlocalmap.entry e = Map.getentry (this);            if (E! = null)                return (T) e.value;        }        return Setinitialvalue ();}

Code Snippet 1

Three ThreadLocalThe object release problem

3.1 How does the thread local variable be recycled when we use the ThreadLocal process, after the thread ends?

First, the map that holds the thread local variable is not a member variable of ThreadLocal , but a member variable of Java.lang.Thread. In other words, when the thread ends, the map's resources are also recycled.

Analytical:

ThreadLocal 's Set,get method obtains the map in the following way:

Threadlocalmap map = getmap (t);

The code for the Getmap method is as follows:

Threadlocalmap Getmap (Thread t) {

return t.threadlocals;

}

Code Snippet 2

Visible: The Threadlocalmap instance is stored as a member variable of java.lang.Thread, and each thread has a unique threadlocalmap. This map takes the ThreadLocal object as key and the thread local variable as the value, so you can save multiple thread local variables under one thread. For ThreadLocal operation, the actual delegate to the current thread, each thread will have its own independent Threadlocalmap instance, the storage warehouse is entry[] Table;entry key is ThreadLocal, value is the storage content, so in the concurrency environment, there is no problem with the set or get of ThreadLocal . The following is the storage diagram for thread local variables:

Storage diagram for "Thread local variables"

Since Treadlocalmap is a member variable of java.util.Thread,threadLocal is the key value in Threadlocalmap, and only one thread local variable can be saved in one. The benefits of Threadlocalmap as a member variable of the thread class are:

A. When a thread dies, the threadlocalmap is recycled, and the saved thread local variable can be reclaimed at the same time if no other references exist.

B. Under the same thread, you can have multiple treadlocal instances, saving multiple "thread local variables."

3.2 If the thread pool is always there, and the threadLocal is recycled in multiple places, will it cause the threadLocal object not to be recycled?

As shown below:

ThreadLocal threadLocal ThreadLocal threadLocal. Set (b);} Public byte[] Getandprint () {byte[] b=threadLocal. get (); System.out.println (b.length); return b;}}

Code Snippet 3

Because Threadlocalmap's entry is a weak reference (WeakReference), when the threadLocal object is no longer referenced externally, the thread map threadLocal The corresponding key and its value are released without causing a memory overflow. The new threadlocaldomail in the Testmain code above is discarded after each loop, can be reclaimed by the garbage collector, and the code can be run continuously without memory overflow.

Four ThreadLocalThe application

In the more familiar two frameworks, Struts2 and hibernate have ThreadLocal variables and are a very central part of the framework.

An important upgrade of STRUTS2 and Struts1 is the decoupling of Request,response two objects, and the Request,response parameter is no longer required in the Struts2 action method. But Struts2 does not pass the method directly into the Request,response object, then how are these two values passed?

The Struts2 uses exactly the ThreadLocal variable. Each time a request is received, STRUTS2 is placed in the Actioncontext instance by placing the Request,response object before the interceptor and action are called, and the actioncontext instance acts as " Thread local variables "are stored in ThreadLocal actioncontext .

Actioncontext implements Serializable {    ThreadLocal actioncontextThreadLocal(); . . .

Code Snippet 4

Since actioncontext is a thread local variable, we get the request object for this thread through Servletactioncontext.getrequest (), and in any class of the local thread, This method can be used to get "thread local variables" without the need for value passing, so that the action class can become a simple class without inheriting any of the parent classes of STRUTS2.

When using hibernate to develop DAO module, we have the most dealings with the session, so how to manage the session reasonably and avoid the frequent creation and destruction of the session is very important for improving the performance of the system. The commonly used Hibernate factory class will save the thread's session through ThreadLocal , so that we process in the same thread, the factory class's GetSession () method, That is, you can get the same session more than once, and the CloseSession method can close the session correctly without passing in the parameters.

V. Use of ThreadLocalProblems that occur

In the Web server environment, because the Tomcat,weblogic and other servers have a thread pool concept, that is, after receiving a request, directly from the thread pool to get the thread processing request, after the request response is completed, the thread itself will not end, but into the thread pool, which can reduce the creation of threads, The overhead of starting the thread.

Because of the Tomcat thread pool, the value that I originally used for the "thread local variable" that was saved in the next request still exists (the same thread is processed) so that each request takes a value in this thread instead of a memcache value, and if the data in Memcache changes, Can not be updated in a timely manner.

Solution: Call the Remove () method of the business treadlocal after processing is complete, emptying the thread local variables to avoid the old data remaining at the next processing time for this thread. Since the active cleanup requires the use of the Struts2 interceptor, the data is setattribute into the request object in order to solve the problem and finally get the request through Servletactioncontext.getrequest (). In the ointment is a certain coupling with the request object.

How does Sturts2 solve the thread pool problem?

Because the Web server thread is used more than once, it is clear that Struts2 will proactively clear the actioncontext value in thread local variables after the response is completed. In the Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter class of struts2, there is this code snippet:

finally {

Prepare.cleanuprequest (Request);

}

and the Cleanuprequest method has the following code

    public void Cleanuprequest (HttpServletRequest request) {...//omit part of code        actioncontext. SetContext (null);        Dispatcher.setinstance (null);    }

Code Snippet 6

Thus, STURTS2, after the completion of processing, will actively empty the "thread local variables"Actioncontext, to achieve the purpose of releasing system resources.

Vi. Summary

Some suggestions for using ThreadLocal :

1. ThreadLocal should be defined as a static member variable, and the definition in code Snippet 3 is not advocated.

2. Can pass the value passed the parameter, does not pass through the ThreadLocal storage, lest causes the ThreadLocal abuse.

3. In the case of an online pool, it is a good idea to explicitly call the Remove () method when the ThreadLocal business cycle process is complete, emptying the value in thread local variables.

4. Normal use of ThreadLocal does not cause memory overflow, but as described in 3.2, the weak reference is only ThreadLocal, the saved value is still strongly referenced, if ThreadLocal is still strongly referenced by other objects, "thread local variables" cannot be reclaimed.

Above is my ThreadLocal object of some understanding, if there is insufficient, also please correct me.

JAVA ThreadLocal Object Servletactioncontext

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.