簡體   English   中英

從ConcurrentHashMap中刪除

[英]Removing from a ConcurrentHashMap

我正在嘗試從ConcurrentHashMap刪除某些條目。 但是,由於這是在多線程環境中發生的,因此可以在進行迭代時刪除和/或修改條目。 當發生這種情況時,迭代器上的remove方法將刪除該條目,即使該條目是自從next接收以來已被修改的。 我構建了一個示例程序來說明這一點:

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

map.put("foo", "bar");
map.put("quz", "qaz");

CountDownLatch foundBar = new CountDownLatch(1);
CountDownLatch doneModifying = new CountDownLatch(1);
CountDownLatch doneIterating = new CountDownLatch(1);

new Thread(() -> {
    try {
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            if (entry.getValue().equals("bar")) {
                foundBar.countDown();
                doneModifying.await();
                it.remove();
            }
        }
        doneIterating.countDown();
    } catch (InterruptedException e) {
        throw new Error(e);
    }
}).start();

foundBar.await();
map.put("foo", "nob");
doneModifying.countDown();

doneIterating.await();
System.out.println(map);

輸出將是{quz=qaz}而不是我期望的{quz=qaz,foo=nob} 我的問題是:如何實現所需的行為? 迭代過程中Map上的remove(key, value)方法是否正確?

是的,您應該使用兩個參數remove方法。 盡管對於大多數Java集合而言,迭代期間直接進行集合突變通常是一件壞事,但ConcurrentHashMap允許這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM