Java Remove Specific Item From ConcurrentHashMap

Related searches

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?

Example Code:

    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);
    }

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);
}

where ConcurrentHashMap.Segment#remove(key, hash, null) is defined as:

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

Note the Javadoc description:

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 Remove Specific Item From ConcurrentHashMap, The remove method does synchronize on a lock. Indeed checking the code of ConcurrentHashMap#remove() , there is a call to a lock method� The remove (Object key, Object value) method of class ConcurrentHashmap in Java is used to remove a mapping from the map. The mapping with the specified (key, value) pair is searched in the map and remove, if found, and return true. If the key does not exist in the map, then this function does nothing and returns false.

An Iterator should do the job:

Iterator<Map.Entry<String, Integer>> iterator = storage.entrySet().iterator();
while(iterator.hasNext())
{
    Map.Entry<String, Integer> entry = iterator.next();
    if(entry.getKey().equals("First"))
    {
       iterator.remove();
    }
 }

Reference: https://dzone.com/articles/removing-entries-hashmap

java.util.concurrent.ConcurrentHashMap.remove java code , How to use. remove. method. in. java.util.concurrent.ConcurrentHashMap Helper method to have a single point of deletion in the queued flows */ public void dequeue(final incrementAndGet(); Object value = core.get(key); core.put( key,new� The remove() method is used to remove the mapping for the specified key from this map if present. Declaration Following is the declaration for java.util.HashMap.remove() method.

You can use directly removeIf on the entrySet :

map.entrySet().removeIf( entry -> .. some condicion on entry ) 

Pay attention there is a bug in Java 8 that is only fixed from Java 9 ( here ).

Java ConcurrentHashMap remove() Method, Java ConcurrentHashMap remove() Method with Examples on java, concurrenthashmap class, public V remove(Object key); public boolean remove(Object key, Object value) value - value expected to be associated with the specified key� The method remove (Object key) internally calls remove (Object key, Object value) where it passed 'null' as a value. Since we are going to remove an element from a Segment, we need a lock on the

ConcurrentHashMap (Java Platform SE 8 ), remove. public boolean remove(Object key, Object value). Removes the entry for a key only if currently mapped to a given value. This� The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. The view's iterators and spliterators are weakly consistent.

ConcurrentHashMap.Remove(Object, Object) Method (Java.Util , Removes the entry for a key only if currently mapped to a given value. C# Copy. [ Android.Runtime.Register("remove", "(Ljava/lang/Object;Ljava/lang/Object;)Z",� If time difference is more than 5 seconds then just delete element from crunchifyMap; Point-3. During add and remove operation print element on Eclipse console; 1st added element will be removed 1st and so on; Please check Eclipse console output for result; Here is a Java program:

HashMap member function entrySet () returns a set of Entry<K,V> in the HashMap and its backed by HashMap i.e. any items remover from the Entry Set will be removed from HashMap too. So lets Iterate over the HashMap using Entry Set Iterator and remove all the elements whose value is 10 while Iterating i.e. // Create a Iterator to EntrySet of HashMap

Comments
  • "I've read an article that synchronization hasn't been added to the remove method" Was that article written about the times of Java 5,6,7, or 8? Maybe it was written with an older Java version in mind.
  • Hopfully this link works javarevisited.blogspot.ca/2013/02/…. He says "Since update operations like put(), remove(), putAll() or clear() is not synchronized Read more: javarevisited.blogspot.com/2013/02/… "
  • @peter.petrov - Calling the remove method on a ConcurrentHashMap like I did in my code example is okay, correct? thread-safety shouldn't be an issue?
  • Not fully sure. What this article means, I guess, is the following: in remove not the whole table is locked but only a given segment of it (as visible in the code posted by manouti). At least that's how I am reading the article and its meaning. So it all depends on your concurrency scenario. Not sure, need to research this myself from scratch if I am to answer it with certainty.
  • @peter.petrov - Hm, How then would I remove a specific item from a concurrecthashmap?
  • The remove method I used in my code example is okay then, right? I don't have to worry about thread-safety?
  • Yes it is fine. It is thread-safe in that no locking is needed to use it and no ConcurrentModificationException would occur.
  • Again: the author just says that remove is not synchronized on the whole table object. That's how I am reading it at least.
  • @peter.petrov - Just to confirm, and I'll let go of this situation, the way I called it on my example code above is fine, I don't have to worry about thread-safety?
  • @spudone Yes, there's no contradiction in that. They are thread-safe, it's the level of consistency here which is being discussed (see the javadoc mahouti posted). So e.g. I guess in some convoluted scenario a get operation might see that something is in the table which is already removed from it :) That's how I am reading all this. Think about an analogue with RDBMS and isolation levels. Hope you see what I mean.