ConcurrentMap in Java


JavaViews 1524

In this article, we will read ConcurrentMap in Java.

ConcurrentMap in Java

Java ConcurrentMap interface

ConcurrentMap interface in Java is a synchronized map that allows more than one thread to access the map. It is thread-safe and doe not affect the consistency of the map elements. It is part of the java.util.concurrent package and is available from JDK 1.5 onwards. The ConcurrentMap interface extends the Map interface.

Classes that implement ConcurrentMap

ConcurrentMap in Java is an interface and hence requires classes to implement its methods. For this, we can either use the ConcurrentSkipListMap or the ConcurrentHashMap.

ConcurrentMap in Java

Methods of ConcurrentMap in Java

Below are the methods present in the ConcurrentMap interface in Java. It also imports all the main methods that are present in the Map interface.

MethodDescription
Object compute(Object key, BiFunction remappingFunction)Attempts to map the specified key with a value
Object computeIfAbsent(Object key, BiFunction remappingFunction)Attempts to map if the specified key does not have any value
Object computeIfPresent(Object key, BiFunction remappingFunction)Attempts to map if the specified key is already associated with a value
void forEach(BiAction action)Performs the specified action for all the elements in the map
Object getOrDefault(Object key,Object defaultValue)Returns the value for the specified key if present else returns the specified default value
Object merge(Object key, Object value, BiFunction remappingFunction)Associates the specified value for the specified key if it is not having any previous value
Object putIfAbsent(Object key, Object value)Associates the specified with the specified value if it does not have any
boolean remove(Object key, Object value)Removes the specific entry if the specified key has the specified value
Object replace(Object key, Object value)Replaces with the new value, if the specified key is present
Object replace(Object key, Object oldValue, Object newValue)Replaces the entry for the specified key with the new value
void replaceAll(BiFunction function)Replaces all the entries in the map using the given function

Example: Insert elements in ConcurrentMap in Java

We can insert elements into a Java ConcurrentMap using the put() method. We can add the entries as a key-value pair. This example shows how to insert an Integer-String as key-value pair. The putIfAbsent() method inserts the entry if there is no value mapping for the specified key.

import java.util.concurrent.*;

public class ConcurrentMapDemo {

  public static void main(String[] args) {
    ConcurrentMap<Integer,String> cm = new ConcurrentHashMap<Integer,String>();
    cm.put(111, "Aarthi");
    cm.put(222, "Banu");
    cm.put(333, "Chetan");
    
    cm.putIfAbsent(444, "Devi");
    
    System.out.println(cm);
  }

}
{444=Devi, 333=Chetan, 222=Banu, 111=Aarthi}

Example: Remove elements

The below example shows how to remove elements from the ConcurrentMap in Java. For this, we can use the remove() method either by specifying only key or both key-value. If we pass both key-value in the remove() method, the specific key-value mapping is not present, it does not remove the entry with the specified key.

import java.util.concurrent.*;

public class ConcurrentMapDemo {

  public static void main(String[] args) {
    ConcurrentMap<Integer,String> cm = new ConcurrentHashMap<Integer,String>();
    System.out.println("Insert elements...");
    cm.put(111, "Aarthi");
    cm.put(222, "Banu");
    cm.put(333, "Chetan");
    
    cm.putIfAbsent(444, "Devi");
    
    System.out.println(cm);
    
    System.out.println("Removing elements...");
    cm.remove(222);
    cm.remove(333, "Chetan");
    System.out.println(cm);
  }

}
Insert elements...
{444=Devi, 333=Chetan, 222=Banu, 111=Aarthi}
Removing elements...
{444=Devi, 111=Aarthi}

Example: Access elements

The below example shows how to access different elements from the ConcurrentMap. The get() method returns the value of the specified key. The getOrDefault() method returns the value of the specified key if present else returns the default value. We can also check if the specified key is present using the containsKey() and specified value using the containsValue() method. It returns true if present else returns false.

import java.util.concurrent.*;

public class ConcurrentMapDemo {

  public static void main(String[] args) {
    ConcurrentMap<Integer,String> cm = new ConcurrentHashMap<Integer,String>();
    System.out.println("Insert elements...");
    cm.put(111, "Aarthi");
    cm.put(222, "Banu");
    cm.put(333, "Chetan");
    
    cm.putIfAbsent(444, "Devi");
    
    System.out.println(cm);
    
    System.out.println(cm.get(111));
    System.out.println(cm.getOrDefault(555, "Default"));
    System.out.println(cm.getOrDefault(333, "Default"));
    System.out.println(cm.containsKey(222));
    System.out.println(cm.containsKey(555));
    System.out.println(cm.containsValue("Banu"));
    System.out.println(cm.containsValue("Eesha"));
    
  }

}
Insert elements...
{444=Devi, 333=Chetan, 222=Banu, 111=Aarthi}
Aarthi
Default
Chetan
true
false
true
false

Example: Iterate elements

We can iterate through all elements in the ConcurrentMap by using an iterator over the entrySet. Using the getKey() method, we can retrieve the key and using the getValue() method, we can retrieve the value. We can also retrieve the keys alone using the keySet() and values using the values() method.

import java.util.Iterator;
import java.util.concurrent.*;

public class ConcurrentMapDemo {

  public static void main(String[] args) {
    ConcurrentMap<Integer,String> cm = new ConcurrentHashMap<Integer,String>();
    cm.put(111, "Aarthi");
    cm.put(222, "Banu");
    cm.put(333, "Chetan");
    
    cm.putIfAbsent(444, "Devi");
    
    Iterator<ConcurrentHashMap.Entry<Integer,String>> it = cm.entrySet().iterator();
    while(it.hasNext()) {
      ConcurrentHashMap.Entry<Integer,String> e = it.next();
      System.out.println("Key:" + e.getKey() + " " + "Value: " + e.getValue());
    }

    System.out.println("Key Set: " + cm.keySet());
    System.out.println("Values: " + cm.values());
      
  }

}
Key:444 Value: Devi
Key:333 Value: Chetan
Key:222 Value: Banu
Key:111 Value: Aarthi
Key Set: [444, 333, 222, 111]
Values: [Devi, Chetan, Banu, Aarthi]

Example: Replace elements

This example shows to replace elements using the replace() method. It replaces the old value with the specified new value for the mentioned key.

import java.util.Iterator;
import java.util.concurrent.*;

public class ConcurrentMapDemo {

  public static void main(String[] args) {
    ConcurrentMap<Integer,String> cm = new ConcurrentHashMap<Integer,String>();
    System.out.println("Insert elements...");
    cm.put(111, "Aarthi");
    cm.put(222, "Banu");
    cm.put(333, "Chetan");
    
    cm.putIfAbsent(444, "Devi");
    System.out.println(cm);
    
    cm.replace(222, "Bharati");
    cm.replace(333, "Chetan", "Chitra");
    System.out.println("Elements after replace operation:");
    System.out.println(cm);
    
  }

}
Insert elements...
{444=Devi, 333=Chetan, 222=Banu, 111=Aarthi}
Elements after replace operation:
{444=Devi, 333=Chitra, 222=Bharati, 111=Aarthi}

 

Reference Reference2

Translate ยป