java - 在 Thread 对象本身中存储线程特定的变量

标签 java multithreading

我正在阅读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/

相关文章:

java - 使用 Swing 时的竞争条件 (?)

java - 如何让maven使用测试资源

java - Android Studio 中缺少向 androidX 的迁移

c# - c#的无锁哈希表

java - 有哪些库可以在 Google App Engine/Java Servlet 上处理 XML

javascript - 三个js的loader使用webworker和IndexedDB

c - Freeswitch 阻塞

multithreading - 双重检查锁定的此修复程序有什么问题?

multithreading - _nolock CRT功能

java - 使用 Spring Boot 更改生成的 CXF 服务器的日志级别