Skip to content
Related Articles

Related Articles

ConcurrentMap Interface in java
  • Difficulty Level : Basic
  • Last Updated : 17 Sep, 2020

ConcurrentMap is an interface and it is a member of the Java Collections Framework, which is introduced in JDK 1.5 represents a Map that is capable of handling concurrent access to it without affecting the consistency of entries in a map. ConcurrentMap interface present in java.util.concurrent package. It provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map. It has inherited the Nested Interface Map.Entry<K, V>

HashMap operations are not synchronized, while Hashtable provides synchronization. Though Hashtable is a thread-safe, it is not very efficient. To solve this issue, the Java Collections Framework introduced ConcurrentMap in Java 1.5.

The Hierarchy of ConcurrentMap
 

ConcurrentMap Interface in java

Declaration:



public interface ConcurrentMap<K,V> extends Map<K,V>

Here, K is the type of key Object and V is the type of value Object.

Implementing Classes

Since it belongs to java.util.concurrent package, we must import is using

import java.util.concurrent.ConcurrentMap
                or
import java.util.concurrent.*

The ConcurrentMap has two implementing classes which are ConcurrentSkipListMap and ConcurrentHashMap. The ConcurrentSkipListMap is a scalable implementation of the ConcurrentNavigableMap interface which extends ConcurrentMap interface. The keys in ConcurrentSkipListMap are sorted by natural order or by using a Comparator at the time of construction of the object. The ConcurrentSkipListMap has the expected time cost of log(n) for insertion, deletion, and searching operations. It is a thread-safe class, therefore, all basic operations can be accomplished concurrently.

Syntax:

// ConcurrentMap implementation by ConcurrentHashMap
CocurrentMap<K, V> numbers = new ConcurrentHashMap<K, V>();

// ConcurrentMap implementation by ConcurrentSkipListMap
ConcurrentMap< ? , ? > objectName = new ConcurrentSkipListMap< ? , ? >();

Example:
 

Java




// Java Program to illustrate methods
// of ConcurrentMap interface
import java.util.concurrent.*;
  
class ConcurrentMapDemo {
  
    public static void main(String[] args)
    {
        // Since ConcurrentMap is an interface,
        // we create instance using ConcurrentHashMap
        ConcurrentMap<Integer, String> m = new ConcurrentHashMap<Integer, String>();
        m.put(100, "Geeks");
        m.put(101, "For");
        m.put(102, "Geeks");
  
        // Here we cant add Hello because 101 key
        // is already present
        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("Map contents : " + m);
    }
}


Output

Map contents : {100=Geeks, 101=For, 102=Geeks}

 
 

Basic Methods

1. Add Elements



The put() method of ConcurrentSkipListMap is an in-built function in Java which associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Java




// Java Program to demonstrate adding
// elements
  
import java.util.concurrent.*;
  
class AddingElementsExample {
    public static void main(String[] args)
    {
        // Instantiate an object
        // Since ConcurrentMap
        // is an interface so We use
        // ConcurrentSkipListMap
        ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>();
  
        // Adding elements to this map
          // using put() method
        for (int i = 1; i <= 5; i++)
            mpp.put(i, i);
  
        // Print map to the console
        System.out.println("After put(): " + mpp);
    }
}


Output

After put(): {1=1, 2=2, 3=3, 4=4, 5=5}

2. Remove Elements

The remove() method of ConcurrentSkipListMap is an in-built function in Java which removes the mapping for the specified key from this map. The method returns null if there is no mapping for that particular key. After this method is performed the size of the map is reduced.

Java




// Java Program to demonstrate removing
// elements
  
import java.util.concurrent.*;
  
class RemovingElementsExample {
    public static void main(String[] args)
    {
        // Instantiate an object
        // Since ConcurrentMap
        // is an interface so We use
        // ConcurrentSkipListMap
        ConcurrentMap<Integer, Integer> mpp = new ConcurrentSkipListMap<Integer, Integer>();
  
        // Adding elements to this map
        // using put method
        for (int i = 1; i <= 5; i++)
            mpp.put(i, i);
  
        // remove() mapping associated
        // with key 1
        mpp.remove(1);
  
        System.out.println("After remove(): " + mpp);
    }
}


Output

After remove(): {2=2, 3=3, 4=4, 5=5}

3. Accessing the Elements

We can access the elements of a ConcurrentSkipListMap using the get() method, the example of this is given below.

Java




// Java Program to demonstrate accessing
// elements
  
import java.util.concurrent.*;
  
class AccessingElementsExample {
  
    public static void main(String[] args)
    {
  
        // Instantiate an object
        // Since ConcurrentMap
        // is an interface so We use
        // ConcurrentSkipListMap
        ConcurrentMap<Integer, String> chm = new ConcurrentSkipListMap<Integer, String>();
  
        // insert mappings using put method
        chm.put(100, "Geeks");
        chm.put(101, "for");
        chm.put(102, "Geeks");
        chm.put(103, "Contribute");
  
        // Displaying the HashMap
        System.out.println("The Mappings are: ");
        System.out.println(chm);
  
        // Display the value of 100
        System.out.println("The Value associated to "
                           + "100 is : " + chm.get(100));
  
        // Getting the value of 103
        System.out.println("The Value associated to "
                           + "103 is : " + chm.get(103));
    }
}


Output

The Mappings are: 
{100=Geeks, 101=for, 102=Geeks, 103=Contribute}
The Value associated to 100 is : Geeks
The Value associated to 103 is : Contribute

4. Traversing

We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentSkipListMap.

Java




import java.util.concurrent.*;
import java.util.*;
  
public class TraversingExample {
  
    public static void main(String[] args)
    {
  
        // Instantiate an object
        // Since ConcurrentMap
        // is an interface so We use
        // ConcurrentSkipListMap
        ConcurrentMap<Integer, String> chmap = new ConcurrentSkipListMap<Integer, String>();
  
        // Add elements using put()
        chmap.put(8, "Third");
        chmap.put(6, "Second");
        chmap.put(3, "First");
        chmap.put(11, "Fourth");
  
        // Create an Iterator over the
        // ConcurrentSkipListMap
        Iterator<ConcurrentSkipListMap
                     .Entry<Integer, String> > itr
            = chmap.entrySet().iterator();
  
        // The hasNext() method is used to check if there is
        // a next element The next() method is used to
        // retrieve the next element
        while (itr.hasNext()) {
            ConcurrentSkipListMap
                .Entry<Integer, String> entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
}


Output

Key = 3, Value = First
Key = 6, Value = Second
Key = 8, Value = Third
Key = 11, Value = Fourth

Methods of ConcurrentMap

  • K – The type of the keys in the map.
  • V – The type of values mapped in the map.

METHOD

DESCRIPTION

compute​(K key, BiFunction<? super K,? super

 V,? extends V> remappingFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent​(K key, Function<? super K,? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent​(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
forEach​(BiConsumer<? super K,? super V> action) Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault​(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
 merge​(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
 putIfAbsent​(K key, V value) If the specified key is not already associated with a value, associates it with the given value.
 remove​(Object key, Object value) Removes the entry for a key only if currently mapped to a given value.
 replace​(K key, V value) Replaces the entry for a key only if currently mapped to some value.
 replace​(K key, V oldValue, V newValue) Replaces the entry for a key only if currently mapped to a given value.
 replaceAll​(BiFunction<? super K,? super V,? extends V> function) Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Methods inherited from interface java.util.Map

METHOD

DESCRIPTION

 clear​() Removes all of the mappings from this map (optional operation).
 containsKey​(Object key) Returns true if this map contains a mapping for the specified key.
 containsValue​(Object value) Returns true if this map maps one or more keys to the specified value.
entry​(K k, V v) Returns an immutable Map.Entry containing the given key and value.
 entrySet​() Returns a Set view of the mappings contained in this map.
 equals​(Object o) Compares the specified object with this map for equality.
 get​(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
 hashCode​() Returns the hash code value for this map.
isEmpty​() Returns true if this map contains no key-value mappings.
keySet​() Returns a Set view of the keys contained in this map.
of​() Returns an immutable map containing zero mappings.
of​(K k1, V v1) Returns an immutable map containing a single mapping.
of​(K k1, V v1, K k2, V v2) Returns an immutable map containing two mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3) Returns an immutable map containing three mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) Returns an immutable map containing four mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) Returns an immutable map containing five mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) Returns an immutable map containing six mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) Returns an immutable map containing seven mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) Returns an immutable map containing eight mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) Returns an immutable map containing nine mappings.
of​(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) Returns an immutable map containing ten mappings.
ofEntries​(Map.Entry<? extends K,? extends V>… entries) Returns an immutable map containing keys and values extracted from the given entries.
put​(K key, V value) Associates the specified value with the specified key in this map (optional operation).
putAll​(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map (optional operation).
remove​(Object key) Removes the mapping for a key from this map if it is present (optional operation).
size​() Returns the number of key-value mappings in this map.
values​() Returns a Collection view of the values contained in this map.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentMap.html

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :