最近項目中遇到如下的場景:在執行資料遷移時,需要按照使用者粒度加鎖,是以考慮使用排他鎖,遷移工具和業務服務屬于兩個服務,是以需要使用分布式鎖。
我們使用緩存(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>