Threadlocal Use scenes

Source: Internet
Author: User

In Java multithreaded programming, to ensure secure access to shared variables by multiple threads, synchronized is often used to ensure that only one thread at a time operates on shared variables. However, in some cases, synchronized cannot guarantee the correct reading and writing of shared variables by multithreading. For example, a class has a class variable, which is read and written by multiple class methods, and when multithreading operates instance objects of the class, a class variable read and write error occurs if the thread has read and write to the class variable, even if the synchronized is not valid until the class method is added. Because locks are freed when the same thread is between two call methods, other threads can access the object's class methods and read or modify class variables. In this case, you can place the class variable in an object of type threadlocal, so that the variable has a separate copy in each thread, and there is no phenomenon where one thread reads the variable and the other thread modifies it.

The following examples illustrate:


public class Querysvc {
private String SQL;

private static ThreadLocal Sqlholder = new ThreadLocal ();

Public Querysvc () {

}

public void execute () {
System.out.println ("Thread" + thread.currentthread (). GetId () + "SQL is" + SQL);
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetId () + "thread local variable SQL" + sqlholder.get ());
}

Public String GetSQL () {
return SQL;
}

public void SetSQL (String sql) {
This.sql = SQL;
Sqlholder.set (SQL);

}

}

To illustrate the effect of multithreaded access on class variables and threadlocal variables, class variables SQL and threadlocal variables are set in Querysvc, and an instance object of Querysvc is created first, and then multiple threads are generated. Set a different SQL instance object, and then call the Execute method to read the SQL value to see if it is a value written in the Set method. This scenario is similar to how multiple request threads in a Web application carry different query conditions to a servlet instance, and then the servlet invokes the business object, passing in different query conditions, and finally ensuring that the result of each request is the result of the corresponding query criteria.

The worker threads that use Querysvc are as follows:

public class Work extends Thread {

Private Querysvc querysvc;
private String SQL;

Public Work (querysvc querysvc,string sql) {
This.querysvc = querysvc;
This.sql = SQL;

}


public void Run () {
Querysvc.setsql (SQL);
Querysvc.execute ();
}

}

Run the thread code as follows:

Querysvc qs = new Querysvc ();
for (int k=0; k<10>
String sql = "SELECT * FROM table where id =" + k;
New Work (Qs,sql). Start ();
}

First create a Querysvc instance object, and then create several threads to call the Querysvc set and Execute methods, each thread incoming SQL is not the same, from the run results can be seen in the SQL variable values are not guaranteed in the same value in execute and set, In a Web application, the result of a user query is not the result of its own query criteria, but the result of another user's query condition, and the value in Threadlocal is always the same as the value set in the set, so that thread security is obtained by using threadlocal.

If an object is to be accessed by multiple threads, and the object has a class variable that is read and written by a different class of methods, the threadlocal can be substituted for the class variable for the purposes of obtaining thread safety.

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.