[問題] 想請問一段多執行緒的程式碼

看板java作者 (coolcomm)時間11年前 (2013/01/24 22:06), 編輯推噓0(007)
留言7則, 3人參與, 最新討論串1/1
以下程式碼節錄自org.apache.commons.lang3.builder.HashCodeBuilder private static final ThreadLocal<Set<IDKey>> REGISTRY = new ThreadLocal<>(); static void register(Object value) { synchronized(HashCodeBuilder.class) { if (getRegistry() == null) { REGISTRY.set(new HashSet<IDKey>()); } } getRegistry().add(new IDKey(value)); } 想請問 ThreadLocal不是thread-safe嗎 為甚麼還要加上synchronized關鍵字? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.163.82.56 另外 synchronized(HashCodeBuilder.class) 有什麼特別含意嗎 為什麼不直接寫 synchronized(this)... ※ 編輯: coolcomm 來自: 1.163.82.56 (01/24 22:12)

01/24 22:24, , 1F
因為 register 是 static method,沒有 this
01/24 22:24, 1F

01/24 22:26, , 2F
這寫法在 static method 是很常見的作法 http://goo.gl/ioAvZ
01/24 22:26, 2F

01/24 22:29, , 3F
所以和static void synchronized register完全一樣囉?
01/24 22:29, 3F

01/24 23:16, , 4F
是,但你上面的例子還有個 getRegistry 在外面,所以不同
01/24 23:16, 4F

01/24 23:21, , 5F
嗯 這部分了解了
01/24 23:21, 5F
※ 編輯: coolcomm 來自: 1.163.82.56 (01/24 23:24)

01/26 15:37, , 6F
This is check then act scenario, which is not
01/26 15:37, 6F

01/26 15:39, , 7F
thred safe.
01/26 15:39, 7F
囧 我發現我忘了貼getRegistry()的定義 static Set<IDKey> getRegistry() { return REGISTRY.get(); } 就這樣一行 ※ 編輯: coolcomm 來自: 114.43.180.83 (01/27 09:11) ※ coolcomm:轉錄至看板 Programming 02/05 19:37
文章代碼(AID): #1H0J_st5 (java)