A special thread binding mechanism in Java-threadlocal,java

Source: Internet
Author: User

In the DRP project, we used ThreadLocal to create the Connection connection, which avoids passing the Connection down in the form of a parameter (passing The purpose of the connection is to ensure that the same connection connection is used because of the JDBC transaction requirements . So what if the ThreadLocal is done? What is the difference between it and the sync lock?

is what:


For threadlocal to see English words we can easily understand the local implementation of a thread, but it is not a thread, but a threadlocalvariable (thread local variable). Perhaps it would be more appropriate to name it Threadlocalvar. The thread local variable (ThreadLocal) function is very simple, that is, for each thread that uses the variable to provide a copy of the value of a variable, is a special thread binding mechanism in Java, so that each thread can independently change its own copy, and not with the other thread copy conflict.

What problems to solve:


Threadlocal is a good idea to solve the thread safety problem, there is a map in the Threadlocal class that stores the variable copy of each thread, the key of the element in the map is the thread object, and the value corresponds to the variable copy of the thread, because the key value is not repeatable, each "thread object" A "variable copy" of the corresponding thread, which reaches thread safety.

The data accessed through threadlocal is always related to the current thread, that is, the JVM binds the private local instance access space for each running thread, providing an isolation mechanism for frequently occurring concurrent visits to multithreaded environments.

Using threadlocal can cause the object to achieve thread isolation. The same threadlocal operation different thread, the essence is the individual thread to their own variable operation.


comparison of threadlocal with other synchronization mechanisms:

Same point:

Threadlocal and all other synchronization mechanisms are designed to resolve access violations in multiple threads to the same variable.

Different points:

In the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult.

To illustrate:

For the teacher enigmatic grading, each teacher will take the answer sheet from the questionnaire to take the answers to the exam, in order to avoid the same problem by a number of teachers, need to lock control, to ensure that there is only one teacher in the draw, the other teachers can only wait, only when the teacher to complete the problem, The waiting teacher is not allowed to draw a question. The synchronization mechanism solves the problem of communication between multiple threads in order to synchronize concurrent access of multiple threads to the same resource.

Threadlocal to solve multiple threads of concurrent access from another angle, Threadlocal maintains a copy of the variable that is bound to the thread for each thread, isolating the data from the various thread, and each thread has its own copy of the variable. It is therefore not necessary to synchronize the variable. Most obviously, the THREADLOACL variable is scoped to a thread, and my understanding is that the thread is "proprietary, hogging", and all operations on that variable are done by that thread! Threadlocal provides a thread-safe shared object that, when writing multithreaded code, encapsulates an unsafe whole variable into a threadlocal, or encapsulates the thread-specific state of the object into threadlocal.

To illustrate:

We are now often layered in software, such as MVC, like this horizontal layering, and threadlocal will provide a way to conveniently within the same thread scope, provide a storage space for us to use, to achieve the vertical storage structure, so that we in the same thread range, Get the data we store at another level at any time.

For example: In the business logic layer needs to invoke multiple Dao layer methods, we want to ensure that the transaction (JDBC transaction) to ensure that they are using the same database connection . So how do you make sure you use the same database connection?

The first scenario, create a database connection from the business layer, and then always pass the connection as a parameter to the Dao

The second scenario, using ThreadLocal, each thread has its own copy of the variable, creates a connection from the business logic layer , and then gets the database connection to the Dao layer


code example:


[Java]View Plaincopy print?
  1. /**
  2. * Using threadlocal
  3. * @author Hejingyuan
  4. *
  5. */
  6. Public class ConnectionManager {
  7. //private static threadlocal<connection> connectionholder=new threadlocal<connection> ();
  8. private static threadlocal<connection> Connectionholder = new threadlocal<connection> ();
  9. /** 
  10. * Get Connection
  11. */
  12. public static Connection getconnection () {
  13. //get () returns the value in the current thread copy of this thread's local variable, and if this is the first time the thread calls the method, the replica is created and initialized.
  14. Connection Conn=connectionholder.get ();
  15. //If the corresponding connection is not bound in the current thread
  16. if (conn = = null) {
  17. try {
  18. Jdbcconfig jdbcconfig = Xmlconfigreader.getinstance (). Getjdbcconfig ();
  19. Class.forName (Jdbcconfig.getdrivername ());
  20. conn = Drivermanager.getconnection (Jdbcconfig.geturl (), Jdbcconfig.getusername (), Jdbcconfig.getpassword ());
  21. } catch (ClassNotFoundException e) {
  22. E.printstacktrace ();
  23. throw New ApplicationException ("System error, contact your system administrator");
  24. } catch (SQLException e) {
  25. E.printstacktrace ();
  26. throw New ApplicationException ("System error, contact your system administrator");
  27. }
  28. }
  29. return conn;
  30. }
  31. public static void CloseConnection () {
  32. Connection Conn=connectionholder.get ();
  33. if (conn! =null) {
  34. try{
  35. Conn.close ();
  36. //Clear connection from Threadlocal
  37. Connectionholder.remove ();
  38. }catch (SQLException e) {
  39. E.printstacktrace ();
  40. }
  41. }
  42. }
  43. }


Business Logic Layer:

[Java]View Plaincopy print?
  1. Public void Addflowcard (Flowcard flowcard) throws ApplicationException {
  2. Connection conn=null;
  3. try{
  4. //Get connection
  5. Conn=connectionmanager.getconnection ();
  6. //Start transaction
  7. Connectionmanager.begintransaction (conn);
  8. //Generate flow-alone numbers
  9. String Flowcardvouno=flowcarddao.generatevouno ();
  10. //Add flow to single master information
  11. Flowcarddao.addflowcardmaster (Flowcardvouno, Flowcard);
  12. //Add flow order details
  13. Flowcarddao.addflowcarddetail (Flowcardvouno, Flowcard.getflowcarddetaillist ());
  14. //flowcarddao.addflowcarddetail (Flowcardvouno, Flowcard.getflowcarddetaillist ());
  15. //Commit a transaction
  16. Connectionmanager.committransaction (conn);
  17. }catch (Daoexception e) {
  18. //ROLLBACK TRANSACTION
  19. Connectionmanager.rollbacktransaction (conn);
  20. throw New ApplicationException ("Add flow to single failure");
  21. }finally{
  22. //close connection and clear from Threadlocal
  23. Connectionmanager.closeconnection ();
  24. }
  25. }


Summarize

Of course, threadlocal can not replace the synchronization mechanism, the problem areas are different. The synchronization mechanism is to synchronize multiple threads for concurrent access to the same resource, which is an efficient way to communicate between multiple threads, while threadlocal is a data share that isolates multiple threads, and essentially does not share resources (variables) across multiple threads, which of course does not require synchronization of multiple threads. So, if you need to communicate between multiple threads, use the synchronization mechanism, and if you need to isolate sharing conflicts between multiple threads, you can use threadlocal, which greatly simplifies your program, making the program more readable and concise.

To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts the way of "changing time by Space". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

Contact Life Example: Employee car

synchronization is a company only one car, staff a use when the other people can only wait, only after the use of staff armor, other talents can use

ThreadLocal is the company for each employee with a car, each employee use their own car, the staff between the car does not affect each other, not restricted!

A special thread binding mechanism in Java-threadlocal,java

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.