Java ThreadLocal: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 38: Line 38:
}
}
</pre>
</pre>


=How Do These Look in a YourKit=
=How Do These Look in a YourKit=


[[Image:Thread_Local_Variable_in_YourKit.png]]
[[Image:Thread_Local_Variable_in_YourKit.png]]

Revision as of 02:11, 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