The function and use of threadlocal

Source: Internet
Author: User

Http://www.cnblogs.com/xrq730/p/4854820.html

The role of threadlocal

From the previous analysis of threadlocal, it can be concluded thatthreadlocal is not used to solve multi-threaded access problems for shared objects by threadlocal set () The Threadlocal.threadlocalmap method is set to the thread's own object to be stored by the thread, and the other threads do not need to be accessed or accessed. The threadlocal.threadlocalmap in each thread and the values in Threadlocal.threadlocal are different objects.

As for why you should use threadlocal, consider this question. In the Java Web, write a servlet:

 public class Servlet extends httpservlet{ protected void Doget (HttpServletRequest request, HttpServletResponse response) throws servletexception , IOException {this.doget (request, response);} protected void DoPost (HttpServletRequest request, HttpServletResponse response) throws servletexception , IOException {}}               

I want to get this httpservletrequest in a normal javabean, but I can't pass the parameter by the way:

Class operaterequest{public     String operaterequest ()    {        null;}}

What happens now? The first solution, the Servlet class defines a global httpservletrequest, as to how to define it casually, can be defined as static, can also be defined as non-static but externally provided setter/getter, and then Operaterequest ( ) method to take this global httpservletrequest each time.

Admittedly, this is a viable solution, but there is one big drawback to this solution: competition. Since HttpServletRequest is a global one, it is bound to introduce a synchronization mechanism to ensure thread safety, and introducing a synchronization mechanism means that the time to sacrifice the response to the user----which is intolerable in the Java Web, which focuses on responding to users.

So, we introduced threadlocal, Since Threadlocal.threadlocalmap is thread-specific, other threads cannot access or need access, so we set HttpServletRequest to the threadlocal.threadlocalmap of the thread through threadlocal. Just a few? In this way, in a request where the need to use the httpservletrequest, the use of the Threadlocal get () method to take this httpservletrequest out, is not a good solution?

Threadlocal use

Forget the complex question above, let's take a look at the simple use of threadlocal, first of all threadlocal must be shared globally:

Class tools{    new threadlocal<string>();}  

Write a thread to threadlocal inside the plug value:

PublicClass ThreadlocalthreadExtendsthread{Privatestatic Atomicinteger AI =NewAtomicinteger ();public Threadlocalthread (String name) {superpublic void run () { Span style= "color: #0000ff;" >try {for (int i = 0; i < 3; I++this.getname () + "Get value--->" +  Tools.t1.get ()); Thread.Sleep (200catch (Interruptedexception e) {e.printstacktrace ();}}}  

Write a main function to start three threadlocalthread:

Throws Exception    {        new Threadlocalthread ("Threada" Newthreadlocalthread ("threadb"New Threadlocalthread ("THREADC"); A.start (); B.start (); C.start ();}    

Look at the results of the operation:

Threada Get Value--->1threadc get value--->2threadb get value--->3threadb get value--->4  THREADC Get Value--->6threada get value--->5threadc get value--->8threada get value--->7  THREADB Get Value--->9

See that each thread has its own string and does not affect----because there is absolutely no way to repeat the numbers. With a threadlocal can also set a data more than once, set only means that the thread of the Threadlocal.threadlocalmap in the table of the value of a location is overwritten with the data of your latest settings, For the same Threadlocal object, after set, there is never more data in the table .

Threadlocal again summary

At the end of the last article, there is a summary of how threadlocal works, and here is a summary of threadlocal:

1,threadlocal is not a collection , it does not store any content, really stores the data collection in thread. Threadlocal is just a tool, a tool that sets a value for a position in a table in the threadlocal.threadlocalmap of each thread .

2, synchronization and threadlocal are two ways to solve the problem of data access in multi-threading, the former is the idea of data sharing , the latter is the idea of data isolation.

3, synchronization is a time to change the idea of space, threadlocal is a space to change the idea of time

4, threadlocal since it is related to the thread, then for the Java Web, the value of the threadlocal setting is only valid in one request, is it similar to request? Because the contents of the request are only valid at one time, compare the differences between the two:

(1) threadlocal can only save one value, a request because it is in map form, it is possible to store multiple values in key-value form

(2) threadlocal generally used in frames, request is generally used in the presentation layer, Action, Servlet

The function and use of threadlocal

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.