天天看点

ThreadLocal的使用场景

最近项目中遇到如下的场景:在执行数据迁移时,需要按照用户粒度加锁,因此考虑使用排他锁,迁移工具和业务服务属于两个服务,因此需要使用分布式锁。

我们使用缓存(tair或者redis)实现分布式锁,具体代码如下:

因为每个线程可能携带不同的userid发起请求,因此在这里使用threadlocal变量存放userid,使得每个线程都有一份自己的副本。

举个例子,下面的类为每个线程生成不同的id,当某个线程第一次调用thread.get()时,会为该线程赋予一个id,并且在后续的调用中不再改变。

每个线程会“隐式”包含一份thread-local变量的副本,只要线程还处于活跃状态,就可以访问该变量;当线程停止后,如果没有其他线程持有该thread-local变量,则该变量的副本会提交给垃圾回收器。

<a href="http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable">— one possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (i'm looking at you, simpledateformat). instead, give each thread its own instance of the object.</a>