threadlocal Thread Local Variables

Source: Internet
Author: User

1.ThreadLocal Description

shared data within a thread: methods, expressions, or modules, when they are running on the same thread, they access the same variable and should be accessing the same data. Binds the data to the thread. In other words, things inside my thread are done within my thread, not affected by other threads. The same data object is shared within the thread. That is, in-thread sharing, out-of-line independent.

Public map<thread,integer> threaddata=new hashmap<thread,integer> (); Threaddata.put ( Thread.currentthread,data);

ThreadLocal: is the equivalent of a map that accesses data directly to the current thread. Newthreadlocal.set ()/get, for the same thread object, a Threadlocal object can only encapsulate one data, to encapsulate two data will require two threadlocal exclusive, if you want to encapsulate 100 of data, Then define an object to encapsulate 100 threadlocal objects, and then encapsulate the object.

threadlocal mainly solves the problem that the data data in multi-threading is inconsistent with concurrency. Threadlocal provides a copy of the data that is accessed concurrently in each thread and runs the business through the access replica, which results in memory consumption, which greatly reduces the performance cost of thread synchronization and reduces the complexity of thread concurrency control.

the difference between 2.ThreadLocal and synchronized

Threadlocal cannot use atomic types, only object types. Threadlocal is much simpler to use than synchronized.

Both threadlocal and synchonized are used to solve multi-threaded concurrent access. But there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a lock is used so that a variable or block of code can be accessed by only one thread at a time. Instead, Threadlocal provides a copy of the variable for each thread, so that each thread accesses the same object at a certain time, isolating data sharing from multiple threads. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads.

Synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads.

Of course threadlocal is not a substitute for synchronized, they deal with different problem domains. Synchronized is used to implement synchronization mechanisms and is more complex than threadlocal.

General steps for 3.ThreadLocal use1. In a multithreaded class (such as the Threaddemo Class), create a Threadlocal object threadxxx, which is used to save the object xxx between threads that need to be treated in isolation.
2. In the Threaddemo class, create a Method getxxx () that gets the data to be quarantined, and in the method it is judged that if the Threadlocal object is null, a new () object should be created to isolate the access type and cast to the type to be applied.
3, in the Threaddemo class of the Run () method, through the GetXXX () method to obtain the data to be manipulated, so that each thread can be guaranteed to correspond to a data object, at any time the operation of this object.

4. Apply the Code demo

public class Threadlocaltest {private static threadlocal<integer> ThreadLocal = new Threadlocal<integer> () ;//multithreading shared data public static void main (string[] args) {for (int i = 0; i < 5; i++) {//multiple threads to the Threadlocal value new thread (new Runnable () {@Overridepublic void run () {//synchronized (threadlocaltest.class) {int data = new Random (). Nextint (); System.out.println (Thread.CurrentThread (). GetName () + "has put data:" + data); Threadlocal.set (data); Mythreadscopedata.getthreadinstance (). SetName ("name" + data); Mythreadscopedata.getthreadinstance (). setage (data);//Read the value of threadlocal in multiple classes, you can see that multiple classes share the same data in the same thread new A (). get (); new B (). get ();/}}}). Start ();}} /** * Analog Business Module A * * @author Administrator * */static Class A {public void get () {int data = Threadlocal.get (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "Get data:" + data); Mythreadscopedata myData = Mythreadscopedata.getthreadinstance (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "Getmydata:" +Mydata.getname () + "," + mydata.getage ());}} /** * Analog Business Module B * * @author Administrator * */static class B {public void get () {int data = Threadlocal.get (); System.out.println ("B from" + Thread.CurrentThread (). GetName () + "Get data:" + data); Mythreadscopedata myData = Mythreadscopedata.getthreadinstance (); System.out.println ("B from" + Thread.CurrentThread (). GetName () + "Getmydata:" + mydata.getname () + "," + mydata.getage ()) ;}}} Class Mythreadscopedata {private static threadlocal<mythreadscopedata> map = new threadlocal< Mythreadscopedata> ();p ublic static Mythreadscopedata getthreadinstance () {Mythreadscopedata instance = Map.get (); if (instance = = null) {instance = new Mythreadscopedata (); Map.set (instance);} return instance;} private string Name;private int age;public string getName () {return name;} public void SetName (String name) {System.out.println (Thread.CurrentThread (). GetName () + "SetName:" + name); this.name = n Ame;} public int getage () {return age;} public void Setage (int aGE) {System.out.println (Thread.CurrentThread (). GetName () + "Setage:" + age); this.age = Age;}} 
Console output Results:

Thread-3 has put data: -1350986975thread-1 have put data: -1681440308thread-2 has put the data: -1348632509thread-0 has put dat A:1315014774thread-4 has put data: -129193035thread-3 setname:name-1350986975thread-3 setage: -1350986975Thread-0 setname:name1315014774thread-0 setage:1315014774thread-4 setname:name-129193035thread-4 SetAge: -129193035Thread-2 Setname:name-1348632509thread-2 setage: -1348632509a from Thread-4 get data: -129193035thread-1 setName: name-1681440308a from Thread-4 getmydata:name-129193035,-129193035a to Thread-0 get data:1315014774a from Thread-0 get mydata:name1315014774,1315014774a from Thread-2 get data: -1348632509a from Thread-2 getmydata:name-1348632509,- 1348632509A from Thread-3 get data: -1350986975a from Thread-3 getmydata:name-1350986975,-1350986975thread-1 setage: 16 81440308A from Thread-1 get data: -1681440308b from Thread-4 get data: -129193035b from Thread-3 get data: -1350986975b fr Om Thread-0 get data:1315014774b from Thread-0 getmydata:name1315014774,1315014774b from Thread-2 get data: -1348632509b from Thread-2 getmydata:name-1348632509,-1348632509b From Thread-4 getmydata:name-129193035,-129193035a to Thread-1 getmydata:name-1681440308,-1681440308b from Thread-3 getmydata:name-1350986975,-1350986975b from Thread-1 get data: -1681440308b from Thread-1 getmydata:name-1681440308,- 1681440308

5.web Expansion

Each HTTP request, which is a separate thread, has a separate threadlocal. Using this feature, we can use the threadlocal, the transient access value of the HTTP request life cycle, and pass the value between different classes. such as the transfer of database connections. At this point, we can use the following methods to store values in a Web application without a scope variable:

Request, ThreadLocal, session, application and so on. Its scope is known and not explained in detail here. Now explain the difference between request and threadlocal.

1), access value in different ways.

Request can store multiple values based on the key access value, a request.

Threadlocal can only have one value, Threadlocal get and set methods have no parameter key.

2), the use of different places.

The request is used in the presentation layer, typically in the action and servlet.

Threadlocal can be used anywhere, generally in the framework base class, such as storing the current database connection.


Reprint please declare the source!!!

threadlocal Thread Local Variables

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.