我正在阅读B. Goetz Java Concurrency in practice现在我正在讨论如何 ThreadLocal
作品。我曾经认为它是 Map
-类似的结构,但他说
Conceptually, you can think of a ThreadLocal as holding a Map that stores the thread-specific values, though this is not how it is actually implemented. The thread-specific values are stored in the Thread object itself; when the thread terminates, the thread-specific values can be garbage collected.
他是什么意思?如何在线程中存储线程特定的值?
最佳答案
问题是,如果它是将线程映射到 ThreadLocal 对象中的值,则这些值永远不会被垃圾收集,因为 ThreadLocal 对象永远不会被销毁。
所以它基本上是相反的 - Thread
对象包含映射到其线程特定值的 ThreadLocal
键的映射。这样,一旦线程完成,完整的映射就会被垃圾收集。
还有一些其他的优化,它实际上使用直接的 ThreadLocalMap 实现而不是实现 Map 接口(interface),使用增量哈希码和类似的东西,但基本上的概念是如上所述。
关于java - 在 Thread 对象本身中存储线程特定的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506186/