Java从ConcurrentHashMap中删除特定项

10 java thread-safety concurrenthashmap java.util.concurrent

使用remove()方法好吗?我读过一篇文章,说明同步还没有添加到remove方法中.如何从ConcurrentHashMap中正确删除特定项?

示例代码:

    ConcurrentHashMap<String,Integer> storage = new ConcurrentHashMap<String,Integer>();
    storage.put("First", 1);
    storage.put("Second", 2);
    storage.put("Third",3);


    //Is this the proper way of removing a specific item from a tread-safe collection?
    storage.remove("First");

    for (Entry<String, Integer> entry : storage.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // ...
        System.out.println(key + " " + value);
    }
Run Code Online (Sandbox Code Playgroud)

man*_*uti 2

remove方法确实在锁上进行同步。确实检查了代码ConcurrentHashMap#remove(),有一个lock获取锁的方法的调用:

public V remove(Object key) {
    int hash = hash(key.hashCode());
    return segmentFor(hash).remove(key, hash, null);
}
Run Code Online (Sandbox Code Playgroud)

其中ConcurrentHashMap.Segment#remove(key, hash, null)定义为:

V remove(Object key, int hash, Object value) {
     lock();
     try {
        ...
Run Code Online (Sandbox Code Playgroud)

请注意Javadoc描述:

检索操作(包括get)通常不会阻塞,因此可能与更新操作(包括putremove)重叠。检索反映了最近完成的更新操作在其开始时的结果。对于诸如putAll和 之类的聚合操作clear,并发检索可能仅反映某些条目的插入或删除。类似地,迭代器和枚举返回反映迭代器/枚举创建时或创建后某个时刻哈希表状态的元素。他们ConcurrentModificationException。然而,迭代器被设计为一次只能由一个线程使用。