关于threadLocal。。

来源:百度知道 编辑:UC知道 时间:2024/05/14 15:22:00
谁能给给有关threadLocal简单明了的解释 主要用途

谢谢拉

ThreadLocal, 我到目前还没正式用过这个东西,因为他更多的是被应用于基础架构的编写,在我理解看来, ThreadLocal就是存放Context的地方,这个地方只能是当前的Thread才能访问,他的生命周期是到这个Thread完毕.
文章[1]中的一段说明,我觉得说的很清楚:

So what's the difference between a thread-local variable and a normal variable? When a thread accesses a thread-local variable it has its own independently initialized copy of the variable. Each thread holds an implicit reference to its copy as long as the thread is alive. So when the thread goes away, all of its thread-local instances are subject to gc.
You typically use an anonymous inner class to provide an initial value (if any) using an appropriate constructor and return the newly constructed object.

You can use this ThreadLocal in several situations:

To keep state with a thread (user-id, transaction-id, logging-id)
To cache objects which you need frequently
但是,同时你也要注意Context的cleanup,要不然,他就会变成evil.[2]

今天在TSS链接了一篇关于ThreadLocal的Blog: [3]

总之,什么时候用ThreadLocal呢?需要