Java ThreadLocal

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

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