java - Thread的任务完成后如何清理ThreadLocal的数据

标签 java multithreading threadpool

我有这三个问题:

1.Is there a way to clean ThreadLocal's data when the Thread's task is done.
2.How about when the thread is in ThreadPool.
3.How can I know a Thread is reused and given back to the ThreadPool.

最佳答案

广告 1) 要“清理”ThreadLocal 的数据,只需调用 ThreadLocal#remove() .

广告 2) ThreadLocal 如果被线程池中的 Thread 访问,其行为不会有所不同。

广告 3) 你不能。它高度依赖于您使用的线程池。有些线程池提供了一种 Hook 方式,有些则没有。

旁注:通常,如果线程池的 Thread 是新创建的、重用的或归还的,通常没有任何意义,除非您想扩展现有的线程池。

关于java - Thread的任务完成后如何清理ThreadLocal的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162718/

相关文章:

java - 有没有办法配置jboss在线程执行结束时清除ThreadLocal变量?

c - 多线程 Web 服务器的线程池

java - OSGi 线程永远不会停止运行,为线程定义了固定的生命周期

队列中的 Java 套接字连接

java - 模拟休息模板

c++ - 当指向对象的指针作为参数传递给 std::thread 时的内存可见性

java - "synchronized-with-resource"获取锁对象也必须同步怎么办?

java - 当从外部资源更新表时,Spring Data JPA 不会刷新或清除缓存

java - Gradle war 插件: creates an intermediate directory in project root

multithreading - 调用逐渐变慢