Multithreading (iii) implementing thread-wide sharing of data between modules and inter-threading data Independence (ThreadLocal)

Source: Internet
Author: User

Threadlocal provides a new way to solve the concurrency problem of multi-thread. Java.lang.ThreadLocal is available in the version of JDK 1.2, using this tool class to write graceful multithreaded programs very succinctly, ThreadLocal is not a thread, but a local variable of thread.


1. And the auxiliary code explains the role and purpose of threadlocal: to implement data sharing within a thread, that is, for the same program code, multiple modules share one piece of data while running in the same thread, while another data is shared while running in another thread.



2. Each thread invokes the set method of the global Threadlocal object, which is equivalent to adding a record to its internal map, where key is the respective thread, and value is the values passed in by the respective set method. The Threadlocal.clear () method can be called at the end of the thread, which frees up memory more quickly, and does not invoke it, because the associated threadlocal variable is automatically freed after the threads have finished.



3.ThreadLocal Application Scenarios:
(1) Order Processing includes a series of operations: Reduce inventory, add a flow of accounts, modify the general ledger, these operations to complete in the same transaction, usually the same thread processing, if the accumulation of corporate receivables failed, you should roll back the previous operations, otherwise, commit all operations, This requires that these operations use the same database connection objects, and that the code for those operations is in a different module class.
(2) A bank transfer consists of a series of actions: reducing the balance of the transfer account, increasing the balance of the transferred account, both of which are to be done in the same transaction, they must use the same database connection object, and the code of the transfer and transfer operation is the method of two different account objects respectively.
(3) For example, Strut2 's Actioncontext, the same piece of code is called by different threads, the data that the code operates on is the state and data of each thread, and for different threads, the GetContext method gets the same object, says to the same thread, Regardless of how many times the GetContext method is called and in which module the GetContext method is taken, the same is obtained.
4. Experimental case: Define a globally shared threadlocal variable, and then start multiple threads to store a random value in the threadlocal variable, and then each thread calls the method of the other multiple classes, which reads the value of the threadlocal variable in the methods of the multiple classes. You can see that multiple classes share the same piece of data in the same thread.
5. Implement the encapsulation of the threadlocal variable, so that the outside world does not directly manipulate the threadlocal variable.
(1) For the encapsulation of basic types of data, this application is relatively rare.
(2) Encapsulation of data of an object type is more common, which is to have a class create a separate instance object for each thread.



Example program:

The first implementation method: (But this implementation is not as good as the second implementation method)

Package Cn.itcast.lishehe;import java.util.random;/** Li Shi-June 11, 2015 * Topic requirements: Constructs two threads, requires: * (1) Two-thread concurrency (this requires that you cannot use the Syschroni   zed keyword) * (2) requires two threads to access their respective data MyData objects, without interfering with each other * (Here you can use the Threadlocal object, through set () and get () to get the MyData object related to this thread, but note that it can only associate one data, * Therefore, for multiple data should be encapsulated in a class, which is actually implemented through map) * (3) thread has a, b two modules, sharing data between modules MyData data * * This program is not implemented in a way Threadlocaldatai  Ndependent2.java good. **/public class ThreadLocalDataIndependent1 {static threadlocal<mydata> ThreadLocal = new Threadlocal<my       Data> (); public static void Main (string[] args) {for (int i = 0; i < 2; i++) {New Thread (new Runnable () {@Override public void run () {int data = new Random (). Nextint ();                      The data here must be defined as local variables, otherwise there is no independent MyData between threads MyData = new MyData ();                      Mydata.setname ("name" +data);                      Mydata.setage (data);         Threadlocal.set (MyData);             New A (). get ();                  New B (). get ();          }}). Start ();              }} static class a{public void Get () {MyData MyData = Threadlocal.get (); System.out.println ("A from" +thread.currentthread (). GetName () + "Get MyData:" +mydata.getname () + "          , "+mydata.getage ());              }} static class b{public void Get () {MyData MyData = Threadlocal.get (); System.out.println ("B from" +thread.currentthread (). GetName () + "Get MyData:" +mydata.getname () + "," +m          Ydata.getage ());      }}} class mydata{private String name;      private int age;      Public String GetName () {return name;      } public void SetName (String name) {this.name = name;      } public int Getage () {return age;      public void Setage (int.) {this.age = age;   }        }



Run results


The Second implementation: (the same is true for each request of the user that creates an action instance in struts2)


Package Cn.itcast.lishehe;import java.util.random;/** Li Shi-June 11, 2015 * Topic requirements: Constructs two threads, requires: * (1) Two-thread concurrency (this requires that you cannot use the Syschroni   zed keyword) * (2) requires two threads to access their respective data MyData objects, without interfering with each other * (Here you can use the Threadlocal object, through set () and get () to get the MyData object related to this thread, but note that it can only associate one data, * Therefore, for multiple data should be encapsulated in a class, which is actually implemented through map) * (3) thread has a, b two modules, sharing data between modules MyData data * * This program is implemented in a way more than Threadlocaldatain  Dependent1.java is better.  * Where Struts2 for each request of the user, an action instance is created for processing, and each thread has its own independent data, which is implemented in this way. **/public class ThreadLocalDataIndependent2 {public static void main (string[] args) {for (int i = 0; i < 2;                      i++) {New Thread (new Runnable () {@Override public void run () { int data = new Random (). Nextint ();                      The data here must be defined as local variables, otherwise there is no independent mydata2.getinstance () between threads. SetName ("name" +data);                      Mydata2.getinstance (). setage (data);                      New A (). get ();                  New B (). get ();    }          }). Start ();              }} static class a{public void Get () {MyData2 myData = mydata2.getinstance (); System.out.println ("A from" +thread.currentthread (). GetName () + "Get MyData:" +mydata.getnam          E () + "," +mydata.getage ());              }} static class b{public void Get () {MyData2 myData = mydata2.getinstance (); System.out.println ("B from" +thread.currentthread (). GetName () + "Get MyData:" +mydata.getname () + ",          "+mydata.getage ());      }}} class mydata2{private static threadlocal<mydata2> Threadmap = new threadlocal<mydata2> (); Private MyData2 () {}//There is no need to use the Syschronized keyword public static MyData2 getinstance () {My          Data2 myData = Threadmap.get ();              if (mydata==null) {myData = new MyData2 ();          Threadmap.set (MyData);      } return myData;  }          private String name;      private int age;      Public String GetName () {return name;      } public void SetName (String name) {this.name = name;      } public int Getage () {return age;      public void Setage (int.) {this.age = age;   }        }

Run results


Multithreading (iii) implementing thread-wide sharing of data between modules and inter-threading data Independence (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.