ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap are thread-safe but the retrieval operations do not entail locking i.e. it does not support locking the entire table in a way that prevents all access. This API is fully interoperable to the HashTable in the programs. It is present in java.util.concurrent package.
ConcurrentHashMap extends AbstractMap<K,V> and Object classes. This API does not allow null to be used as a key or value and it is a member of Java Collections Framework.
Type Parameters:
- K – the type of keys maintained by the map
- V – the type of values mapped to it.
All implemented interfaces:
Serializable, ConcurrentMap<K,V>, Map<K,V>
Syntax:
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable
Constructors:
- ConcurrentHashMap() – Creates an empty Map with an initial capacity of 16, load factor of 0.75 and concurrency level of 16.
- ConcurrentHashMap(int initialCapacity) – Creates an empty Map with the given initial capacity and default values of load factor and concurrencyLevel.
- ConcurrentHashMap(int initialCapacity, float loadFactor) – Creates an empty Map with the given initial capacity and given load factor and default concurrencyLevel.
- ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) – Creates an empty Map with given initial capacity, load factor and concurrencyLevel.
- ConcurrentHashMap(Map<? extends K,? extends V> m) – Creates a new Map with the same mappings as given in the Map.
Code:
Java
// Java Program to Implement ConcurrentHashMap APIÂ
import java.util.Collection;import java.util.Enumeration;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;Â
public class ConcurrentMap<K, V> {Â Â Â Â private ConcurrentHashMap<K, V> hm;Â
    // creates an empty ConcurrentHashMap with initial    // capacity 16 and load factor 0.75    public ConcurrentMap()    {        hm = new ConcurrentHashMap<K, V>();    }Â
    // creates an empty ConcurrentHashMap with given initial    // capacity and load factor 0.75    public ConcurrentMap(int incap)    {        hm = new ConcurrentHashMap<K, V>(incap);    }Â
    // creates an empty ConcurrentHashMap with given initial    // capacity and load factor    public ConcurrentMap(int incap, float lf)    {        hm = new ConcurrentHashMap<K, V>(incap, lf);    }Â
    // creates an empty ConcurrentHashMap with given initial    // capacity, load factor and concurrency level    public ConcurrentMap(int incap, float lf,                         int concurrLevel)    {        hm = new ConcurrentHashMap<K, V>(incap, lf,                                         concurrLevel);    }Â
    // Creates an hashMap with the same values as the given    // hashMap    public ConcurrentMap(Map<? extends K, ? extends V> m)    {        hm = new ConcurrentHashMap<K, V>(m);    }Â
    // Removes all the keys and values from the Map    public void clear() { hm.clear(); }Â
    // Return true if the Map contains the given Key    public boolean containsKey(Object k)    {        return hm.containsKey(k);    }Â
    // Return true if the map contains keys that maps to the    // given value    public boolean containsValue(Object v)    {        return hm.containsValue(v);    }Â
    // Returns a set view of the key-value pairs of the map    public Set<Map.Entry<K, V> > entrySet()    {        return hm.entrySet();    }Â
    // Return the value to which the given key is mapped    public V get(Object k) { return hm.get(k); }Â
    // Return true if the map does not contains any    // key-value pairs    public boolean isEmpty() { return hm.isEmpty(); }Â
    // Returns a set view of the key-value pairs of the map    public Set<K> keySet() { return hm.keySet(); }Â
    // Maps the given value to the given key in the map    public V put(K k, V v) { return hm.put(k, v); }Â
    // Copies all the key-value pairs from one map to    // another    public void putAll(Map<? extends K, ? extends V> mp)    {        hm.putAll(mp);    }Â
    // Removes the mapping of the given key from its value    public V remove(Object k) { return hm.remove(k); }Â
    // Returns the size of the map    public int size() { return hm.size(); }Â
    // Returns the collection view of the values of the map    public Collection<V> values() { return hm.values(); }Â
    // Returns an enumeration of the given values of the map    public Enumeration<V> elements()    {        return hm.elements();    }Â
    // If the given key is not associated with the given    // value then associate it.    public V putIfAbsent(K k, V v)    {        return hm.putIfAbsent(k, v);    }Â
    // Replaces the value for a key only if it is currently    // mapped to some value.    public V replace(K key, V value)    {        return hm.replace(key, value);    }Â
    // Replaces the oldValue for a key only if it is    // currently mapped to a given value. *    public boolean replace(K key, V oValue, V nValue)    {        return hm.replace(key, oValue, nValue);    }Â
    public static void main(String[] arg)    {        // Creating an object of the class        ConcurrentMap<Integer, String> hm            = new ConcurrentMap<Integer, String>();Â
        hm.put(1, "Amit");        hm.put(2, "Ankush");        hm.put(3, "Akshat");        hm.put(4, "Tarun");Â
        // Creating another Map        Map<Integer, String> hm2            = new HashMap<Integer, String>();        hm.putAll(hm2);Â
        System.out.println(            "The Keys of the ConcurrentHashMap is ");Â
        Set<Integer> k = hm.keySet();        Iterator<Integer> i = k.iterator();Â
        while (i.hasNext()) {            System.out.print(i.next() + " ");        }        System.out.println();Â
        System.out.println(            "The values of the ConcurrentHashMap is ");Â
        Collection<String> values = hm.values();        Iterator<String> s = values.iterator();Â
        while (s.hasNext()) {            System.out.print(s.next() + " ");        }        System.out.println();Â
        System.out.println(            "The entry set of the ConcurrentHashMap is ");Â
        Iterator<Entry<Integer, String> > er;        Set<Entry<Integer, String> > ent = hm.entrySet();Â
        er = ent.iterator();Â
        while (er.hasNext()) {            System.out.println(er.next() + " ");        }Â
        System.out.println(            "The ConcurrentHashMap contains Key 3 :"            + hm.containsKey(3));Â
        System.out.println(            "The ConcurrentHashMap contains Tarun:"            + hm.containsValue("Tarun"));Â
        System.out.println(            "Put the key 10 with value Shikha if not associated : "            + hm.putIfAbsent(10, "Shikha"));Â
        System.out.println(            "Replace key 3 oldvalue of Akshat and newvalue Pari :"            + hm.replace(3, "Akshat", "Pari"));Â
        System.out.println(            "The Size of the ConcurrentHashMap is "            + hm.size());Â
        // Clearing the Concurrent map        hm.clear();Â
        if (hm.isEmpty())            System.out.println(                "The ConcurrentHashMap is empty");        else            System.out.println(                "The ConcurrentHashMap is not empty");    }} |
The Keys of the ConcurrentHashMap is 1 2 3 4 The values of the ConcurrentHashMap is Amit Ankush Akshat Tarun The entry set of the ConcurrentHashMap is 1=Amit 2=Ankush 3=Akshat 4=Tarun The ConcurrentHashMap contains Key 3 :true The ConcurrentHashMap contains Tarun:true Put the key 10 with value Shikha if not associated : null Replace key 3 oldvalue of Akshat and newvalue Pari :true The Size of the ConcurrentHashMap is 5 The ConcurrentHashMap is empty
