![](/img/trans.png)
[英]what happens if we 'put' and new value to an already existing key in the Linkedhashmap
[英]What happens if multiple put operations are performed on linkedhashmap in parallel?
我有示例代碼:
Map<Integer, String> hs = new LinkedHashMap<>();
IntStream.range(0,1000).parallel().forEach(value -> hs.put(value, "value"));
System.out.println(hs.size());
這永遠不會返回大小為 1000,因為我理解linkedhashmap 不是線程安全的,當我使用Collections.synchronizedMap(new LinkedHashMap<>());
大小始終為 1000,因為它是線程安全的。
我想了解當多個線程嘗試將數據放入其中時,linkedhashmap put 操作會發生什么? 它的條目如何減少?
問問自己鏈接的哈希圖是如何工作的。
顧名思義:通過將對象“鏈接”成某種“鏈”,並使用跟蹤“下一個”元素的數據結構。
現在想象鏈以對象 X 結束,兩個不同的線程進來並添加一個應該在 X 之后的新條目。這兩個線程都更新該數據結構,第二個線程覆蓋第一個線程所做的。
換句話說:應該添加兩個新元素作為 HashMap 鍵,但實際上只有一個成功,另一個根本就丟失了。
這就像兩個人往垃圾桶里扔磚頭。 如果他們不注意,他們可能會同時扔磚塊,磚塊“碰撞”,而不是它們都最終進入垃圾箱。
hs.put(0, "0");
hs.put(1, "1");
hs.put(2, "2");
// hs should be "0 -> 1 -> 2"
hs.put(0, "0");
hs.put(1, "1");
// so sometimes it should be `0.next = 1`
// because it is not thread safe
// `2` should be behind 1, but it cut the queue
// become 0.next = 1; 0.next = 2; `0.next` is assigned twice
// so the `1` is lost!
hs.put(2, "2");
// hs will be "0 -> 2"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.