Analysis of Java threadlocal usage __java

Source: Internet
Author: User

Analysis of Java threadlocal usage

The definition of ThreadLocal in the JAVA API documentation is:

This class provides thread-local variables. These are variables differ from their normal counterparts in so each thread that accesses one (via it get or set method) ha s its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes-Wish to associate state with a thread (e.g., a U Ser ID or Transaction ID).

This class provides a variable that is local to a thread. These variables are independent (must be accessed through the get and set methods) in the case of shared access Chengri the different lines.

It is clear that this class provides a mechanism to prevent the unsafe mechanisms that are brought about by multithreaded access. It's actually a thread that saves a variable locally rather than through a shared variable. This depends on our use of the situation, if we do need to share the data, it is still necessary through the synchronization mechanism to ensure data security. If there are situations where you want different threads to keep the variables separate, it's more appropriate to use this.

ThreadLocal This class itself is not a variable that represents a thread to access, the member variable of this class is. JDK1.5 gives ThreadLocal a generic function, that is, threadlocal<t> this generic T is the local variable to thread. The thread accesses the variable T through the ThreadLocal get and set methods. ThreadLocal provides a mechanism that ensures that a thread accesses a variable of type T by using this to access it as a different copy. So accessing the variable must be accessed by Threadlocal this class with only two public methods, that is, get () and set () methods.

A inintvalue () protected method is also provided. This method is used to initialize the value of the variable.

Note: By default, InitValue () returns NULL. The Get method invokes the InitValue method by default when the thread invokes the first call before the set is invoked. So if you do not overwrite this method, it may cause the get to return null. Of course, this is not the case if the set is invoked. But often in multi-threaded situations we cannot guarantee that each thread calls the set before calling get, so it is best to overwrite initvalue so as not to cause null pointer exceptions.

With so much to say, it's probably better to look at the example below.

Example 1 : No use of Threadlocal:

/**

*

* @author Yblin

* 2009.8.18

*

*/

Public class testwithnothreadlocal {

Public Static int a = 0;


Public Static void Main (string[] args) {

Mythread mythread = new mythread ();

Mythread.start ();

for ( int i = 0; i < 5; i++) {

A = a + 1;

System. Out. println (Thread. CurrentThread (). GetName () + ":" + a);

}

}

Public Static class Mythread extends Thread {

Public void Run () {

for ( int i = 0; i < 5; i++) {

A = a + 1;

System. Out. println (Thread. CurrentThread (). GetName () + ":" + a);

}

}

}


}


One result of running is as follows:

Main:2

Thread-0:2

Main:3

Thread-0:4

Main:5

Thread-0:6

Main:7

Thread-0:8

Main:9

Thread-0:10


In the absence of synchronization mechanism, the result is unsafe for the situation to occur is normal, two threads are 2. Below please see the effect of using the ThreadLocal.


Example 2 : Use of the Threadlocal situation:

/**

*

* @author Yblin

* 2009.8.18

*

*/

Public class TestThreadLocal2 {

Private Static Threadlocal<integer> a = new threadlocal<integer> () {

Public Integer InitialValue () {//initialized, default is return null

return 0;

}

};


Public Static void Main (String args[]) {

Mythread my;

my = new mythread ();

My.start ();

for ( int i = 0; i

Related Article

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.