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
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
* https://www.baeldung.com/java-threadlocal
=Internal=
=Internal=


Line 4: Line 7:


=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]]

Latest revision as of 16:39, 6 August 2020

External

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