Java ThreadLocal: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * java Threads =Overview=")
 
No edit summary
Line 4: Line 4:


=Overview=
=Overview=
<tt>java.lang.ThreadLocal</tt> API provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via ThreadLocal variable's <tt>get()</tt> or <tt>set()</tt> 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).
=Example=
<pre>
public class MyContext {
    private static final ThreadLocal< MyContext > threadLocal = new ThreadLocal<>();
    // Static ----------------------------------------------------------------------------------------------------------
   
    public static void associate(MyContext c) {
        threadLocal.set(c);
    }
    public static MyContext get() {
        return threadLocal.get();
    }
    /**
    * May return null.
    */
    public static MyContext disassociate() {
       
        MyContext c = get();
        threadLocal.remove();
        return c;
    }
  ...
}
</pre>
=How Do These Look in a YourKit=
[[Image:Thread_Local_Variable_in_YourKit.png]]

Revision as of 02:03, 22 July 2016

Internal

Overview

java.lang.ThreadLocal API provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via ThreadLocal variable's 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).

Example

public class MyContext {

    private static final ThreadLocal< MyContext > threadLocal = new ThreadLocal<>();

    // Static ----------------------------------------------------------------------------------------------------------
    
    public static void associate(MyContext c) {
        threadLocal.set(c);
    }

    public static MyContext get() {
        return threadLocal.get();
    }

    /**
     * May return null.
     */
    public static MyContext disassociate() {
        
        MyContext c = get();
        threadLocal.remove();
        return c;
    }

   ...

}


How Do These Look in a YourKit

Thread Local Variable in YourKit.png