Thread security and threadlocal

Source: Internet
Author: User

Original post address: http://javapapers.com/core-java/threadlocal/

Try to translate. Thank you for your criticism.

 

Address: http://javapapers.com/core-java/threadlocal/

The core concept of threadlocal is that no thread can use the get or set method to access its own copy of the independently initialized variable.

1. threadlocal Introduction

To avoid any conflicts in a multi-threaded environment, we hope to separate multiple instances of a class. For each thread, no instance is unique. This is just a way to implement thread security.

Another important aspect of thread security is global access. It can be accessed anywhere inside the thread. Remember: It should be declared static and final.

2. What is thread security?

A thread is a separate line of a process. When we talk about multi-threaded applications, we mean that multiple threads of a process access the same line of code. In this case, there is a possibility that one thread can access or modify the data of another thread. When data cannot be shared like this, we should make it thread-safe. There are several ways to implement thread security:

· Re-import

· Mutex (synchronization mechanism)

· Threadlocal

· Atomic operations

3. Use threadlocal

(Reference Joshua Bloch. It's a huge abstraction. I don't understand it ,......)

We have a non-thread-safe variable. If we want to change it to thread-safe, we can consider the synchronization mechanism to close the object to the synchronization block. The other method is to use threadlocal to keep individual objects for each thread safe.

4. Example of threadlocal

Package com. javapers;

 

Import java. Text. simpledateformat;

Import java. util. date;

 

Public class threadlocalexample {

Private Static final threadlocal formatter = new threadlocal (){

 

Protected simpledateformat initialvalue (){

Return new simpledateformat ("yyyymmdd hhmm ");

}

};

 

Public String formatit (date ){

Return formatter. Get (). Format (date );

}

}

In the above Code, the key is to understand the get () method. It returns a copy of The threadlocal variable of the current thread. If the variable of the current thread does not have a value, the value of the first Initialization is returned by calling the initalvalue method.

Javadoc examples

The following example generates a unique identifier for each thread. The ID of a thread is specified when the get method is called for the first time and remains unchanged in subsequent calls.

Port java. util. Concurrent. Atomic. atomicinteger;

 

Public class threadid {

// Atomic integer containing the next thread ID to be assigned

Private Static final atomicinteger nextid = new atomicinteger (0 );

 

// Thread Local variable containing each thread's ID

Private Static final threadlocal threadid =

New threadlocal (){

@ Override protected integer initialvalue (){

Return nextid. getandincrement ();

}

};

 

// Returns the current thread's unique ID, assigning it if necessary

Public static int get (){

Return threadid. Get ();

}

}

5. threadlocal usage in Java APIs

In jdk1.7, we have a new class named threadlocalrandom. It is used to generate random numbers for parallel threads. Each thread is the seed of random numbers and is unique. This is a very cool feature.

The following code implements threadlocal in the above class:

Private Static final threadlocal localrandom =

New threadlocal (){

Protected threadlocalrandom initialvalue (){

Return new threadlocalrandom ();

}

};

Use threadlocalrandom

Package com. javapers;

 

Import java. util. Concurrent. threadlocalrandom;

 

Public class threadlocalrandomexample {

 

Public static void main (string ARGs []) throws interruptedexception {

 

// Tossing 3 Coins

For (INT I = 0; I <3; I ++ ){

Final thread = new thread (){

 

Public void run (){

System. Out. Print (thread. currentthread (). getname () + ":");

 

// Generating 3 random numbers-random for every thread

For (Int J = 0; j <3; j ++ ){

Final int random = threadlocalrandom. Current (). nextint (

1, 3 );

System. Out. Print (random + ",");

}

System. Out. println ();

}

};

Thread. Start ();

Thread. Join ();

}

}

}

6. threadlocal and Memory leakage

Threadlocal is not a devil, but an excellent and practical API. It depends on how we use it. We should learn to use appropriate tools in the right place. We cannot use cannons to fight mosquitoes, but we cannot condemn them.

 

PDF File Download:

Http://download.csdn.net/detail/licl19870605/4529958

 

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.