The threadlocal in Java uses

Source: Internet
Author: User

Threadlocal is used for the following scenarios:

1. Resources that are not allowed to be accessed concurrently by multiple threads

2. Single thread survival process uses only one instance

The official definition is as follows:



Private static fields in classes this wish to associate state with a thread (e.g., a user ID or Transaction ID).

Examples of Use (official example: each thread has its own individual ID, and this ID remains self-increasing as new threads are added):

 ImportJava.util.concurrent.atomic.AtomicInteger; Public classThreadId {//Atomic integer containing the next thread ID to be assigned     Private Static FinalAtomicinteger NextID =NewAtomicinteger (0); //thread local variable containing each Thread ' s ID     Private Static FinalThreadlocal<integer> threadId =NewThreadlocal<integer>() {@OverrideprotectedInteger InitialValue () {returnnextid.getandincrement ();     }     }; //Returns The current thread ' s unique ID, assigning it if necessary      Public Static intget () {returnThreadid.get (); } }

This article is no longer detailed in the source code, interested students can read their own source code.

Reference:

Https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

The threadlocal in Java uses

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.