关于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呢?需要一些Thread-safe的全局变量,但是用他的时候,记得最后清空,要不然会导致memory-leak.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值