【譯】java.lang.ThreadLocal

來源:互聯網
上載者:User

標籤:cin   time   and   rri   var   depend   override   garbage   erp   

This class provides thread-local variables. These variables differ from their normal counterparts(副本) in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically(代表的) private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, the class below generates 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 AtomicInteger nextId = new AtomicInteger(0);     // Thread local variable containing each thread‘s ID     private static final ThreadLocal<Integer> threadId =         new 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.get();     } } 

Each thread holds(擁有) an implicit(隱式的) reference to its 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 are subject to garbage(garbage) collection (unless other references to these copies exist).

【譯】java.lang.ThreadLocal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.