ConcurrentMap Interface in java

ConcurrentMap: ConcurrentMap is an interface, which is introduced in JDK 1.5 represents a Map which is capable of handling concurrent access to it and ConcurrentMap interface present in java.util.concurrent package.The ConcurrentMap provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map.

Hierarchy of ConcurrentMap interface:

It extends map interface in Java. Below are specific methods of ConcurrentMap interface:



  • Object putIfAbsent(K key, V value):If the specified key is not already associated with a value, associate it with the given value.
  • boolean remove(Object key, Object value):Removes the entry for a key only if currently mapped to a given value.
  • boolean replace(K key, V oldValue, V newValue):Replaces the entry for a key only if currently mapped to a given value.
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate methods 
// of ConcurrentMap interface
import java.util.concurrent.*;
class ConcurrentMapDemo {
    public static void main(String[] args)
    {
        ConcurrentHashMap m = new ConcurrentHashMap();
        m.put(100, "Geeks");
        m.put(101, "For");
        m.put(102, "Geeks");
  
        // Here we cant add Hello because 101 key
        // is already present in ConcurrentHashMap object
        m.putIfAbsent(101, "Hello");
  
        // We can remove entry because 101 key
        // is associated with For value
        m.remove(101, "For");
  
        // Now we can add Hello
        m.putIfAbsent(101, "Hello");
  
        // We can replace Hello with For
        m.replace(101, "Hello", "For");
        System.out.println(m);
    }
}

chevron_right


Output:

{100=Geeks, 101=For, 102=Geeks}


My Personal Notes arrow_drop_up

Hello everyone, I am Bishal KUMAR Dubey and most importantly an idea creator I just love Programming languages and love to know new concepts everyday,every minute,every second Here to help Other GEEKS

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.