Java Multithreaded Learning-threadlocal

Source: Internet
Author: User
Tags unique id

In order to make up the word, the Oracle document introduced threadlocal copied over

Threadlocal<t>extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in so each thread this accesses one (via itsGetOrSetmethod) has its own, independently initialized copy of the variable.ThreadLocalInstances is typically private static fields in classes this wish to associate state with a thread (e.g., a user ID or Tr Ansaction ID).

For example, the class below generates a unique identifiers local to each thread. A thread ' s ID is assigned the first time it invokes Threadid.get () and remains unchanged on subsequent calls.

Import Java.util.concurrent.atomic.AtomicInteger; public class ThreadId {     //Atomic integer containing the next thread ID to be assigned     private static final Atomic Integer NextID = new Atomicinteger (0);     Thread local variable containing each thread ' s ID     private static final threadlocal<integer> threadId =         NE W threadlocal<integer> () {             @Override protected Integer initialvalue () {                 return nextid.getandincrement () ;         }     };     Returns the current thread's unique ID, assigning it if necessary public     static int get () {         return THREADID.G ET ();     

Each thread holds an implicit reference to their copy of a thread-local variable as long as the thread is alive and the threadlocal instance is accessible; After a thread goes away, all of its copies of Thread-local instances is subject to garbage collection (unless other Refe Rences to these copies exist).

Java Multithreaded Learning-threadlocal

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.