Whisk off ThreadLocal's gossamer

Posted by alfoxy on Wed, 01 Apr 2020 07:37:15 +0200

What kind of ghost is ThreadLocal's veil blowing away?

You, you, and have you ever used threadLocal? The answer is obvious. But it is often mentioned.

The following is the explanation of API:
This class provides thread local variables. These variables are different from their normal counterparts because each thread accessing a variable (through its get or set method) has its own local variable, which is independent of the initialization copy of the variable. ThreadLocal instances are usually private static fields in a class that want to associate a state with a thread, such as a user ID or transaction ID.

Well, ThreadLocal is the local variable copy of a thread. Each thread holds its own copy. As the thread's life cycle ends, it is automatically destroyed.

package test.com;

public class TestImpl implements Test{

    @Override
    public void init(Integer i) {
        // TODO Auto-generated method stub
        ThreadLocal<Integer> tl = Main3.local;
        Integer init = tl.get();
        //Initialize a thread variable if it is not initialized
        if(init==null) {

            System.out.println("initing...");
            tl.set(i);
        }
    }

    @Override
    public void execute() {
        // TODO Auto-generated method stub
        System.out.println(Main3.local.get());
    }

}


package test.com;

public class Main3 {

    public static ThreadLocal<Integer> local = new ThreadLocal<>();

    public static void main(String[] args) {

        TestImpl impl = new TestImpl();
        impl.execute();
        impl.init(2);
        impl.execute();

        System.out.println("--------------------------");
        TestImpl impl2 = new TestImpl();

        impl2.execute();
        impl2.init(5);
        impl2.execute();
        impl.execute();

        System.out.println("-------------------------");

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                TestImpl impl3 = new TestImpl();
                impl3.init(10);
                impl3.execute();
            }
        });

        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("-------------------------");

        impl.execute();
        impl2.execute();
    }
}

//results of enforcement
null
initing...
2
--------------------------
2
2
2
-------------------------
initing...
10
-------------------------
2
2

//Analysis: from the execution result of the program, it can be seen that threadloadl will only generate variable copies in the thread, which will be held by the thread,
//It has nothing to do with how many objects are initialized in the thread.

You may say that you can cache something, but one point is that this copy will be destroyed as the thread dies. No management required.