为什么ThreadLocal变量需要静态?

opt*_*nal 6 java multithreading

我已经阅读了很多关于为什么ThreadLocal变量需要是静态的文章(尽管没有必要),但我没有理解为什么它应该是静态的.

我在这里阅读了许多其他链接,但没有得到这个想法.

我做过这样的事情

public class ThreadLocalDemo{

    public static void main(String[]args)throws Exception{
        SharedRersource r1= new SharedRersource();
        Thread t1= new Thread(r1);
        Thread t2= new Thread(r1);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Main thread Exiting...");
        }

    }

class SharedRersource implements Runnable{


        private ThreadLocal<Integer> threadId = new ThreadLocal(){
            protected Integer initialValue(){
                return (int)(Math.random()*100);
                }
        };
        public void run(){

            try{
                Thread.sleep(2000);
            }
            catch(InterruptedException e){
                e.printStackTrace();
                }
                System.out.println(threadId.get());

            }
        };
Run Code Online (Sandbox Code Playgroud)

这里线程t1和t2具有threadId的私有副本,而不是为什么它应该是静态的

请更好地了解我.谢谢

opt*_*nal 7

这个问题的答案在于ThreadLocal的实现.

将ThreadLocal视为容器

ThreadLocal是一个ThreadLocalMap内部维护的容器,这ThreadLocalMap是为什么threadlocal需要是静态的关键(尽管不是必需的,但建议是保持静态).

因为我们想要 single container per class,not container per instance如果我们每个实例都有容器,那么我们将拥有与实例一样多的容器,这会产生内存泄漏.

更多细节在这里

  1. http://www.0xcafefeed.com/2004/06/of-non-static-threadlocals-and-memory/
  2. https://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/