Java从ConcurrentHashMap中删除特定项 [英] Java Remove Specific Item From ConcurrentHashMap

查看:993
本文介绍了Java从ConcurrentHashMap中删除特定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is using the remove() method okay? I've read an article that synchronization hasn't been added to the remove method. How do I properly remove a specific item from a 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);
    }


推荐答案

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

The remove method does synchronize on a lock. Indeed checking the code of ConcurrentHashMap#remove(), there is a call to a lock method that acquires the lock:

public V remove(Object key) {
    int hash = hash(key.hashCode());
    return segmentFor(hash).remove(key, hash, null);
}

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

V remove(Object key, int hash, Object value) {
     lock();
     try {
        ...

注意 Javadoc 说明:


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

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.

这篇关于Java从ConcurrentHashMap中删除特定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆