Java ConcurrentHashMap

ConcurrentHashMap is a class which is available in java.util package. The ConcurrentHashMap is a class of the Java collections framework provides a thread-safe map. That is, multiple threads can access the map at once without affecting the consistency of entries in a map. In Java ConcurrentHashMap, elements are stored in key/value pairs. Keys are unique values associated with individual values. ConcurrentHashMap cannot contains duplicate keys.

ConcurrentHashMap Syntax:
                        
                            ConcurrentHashMap<K, V> numbers = new ConcurrentHashMap<>();
                            ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                        
                    

By default,

  1. the capacity of the ConcurrentHashMap will be 16
  2. the load factor will be 0.75

Basic Operations on Java ConcurrentHashMap
  1. 1. Insert Elements to ConcurrentHashMap
  2. 2. Access ConcurrentHashMap Elements
  3. 3. Remove ConcurrentHashMap Elements
Methods of ConcurrentHashMap
Method Name Description
put() inserts the specified key/value mapping to the map.
putAll() inserts all the entries from the specified map to this map.
putIfAbsent() inserts the specified key/value mapping to the map if the specified key is not present in the map.
entrySet() returns a set of all the key/values mapping (entry) of a map.
keySet() returns a set of all the keys of the map.
values() returns a set of all the values of the map.
get() Returns the value associated with the specified key. Returns null if the key is not found.
getOrDefault() Returns the value associated with the specified key. Returns the specified default value if the key is not found.
remove(key) returns and removes the entry associated with the specified key from the TreeMap.
remove(key, value) removes the entry from the map only if the specified key is associated with the specified value and returns a boolean value.
forEach() The forEach() method iterates over our entries and executes the specified function.
forEachEntry() executes the specified function for each entry.
forEachKey() executes the specified function for each key.
forEachValue() executes the specified function for each value.
search() The search() method searches the map based on the specified function and returns the matched entry.
searchEntries() search function is applied to key/value mappings.
searchKeys() search function is only applied to the keys.
searchValues() search function is only applied to the values.
reduce() The reduce() method accumulates (gather together) each entry in a map. This can be used when we need all the entries to perform a common task, like adding all the values of a map.
reduceEntries() returns the result of gathering all the entries using the specified reducer function.
reduceKeys() returns the result of gathering all the keys using the specified reducer function.
reduceValues() returns the result of gathering all the values using the specified reducer function.
1. Insert Elements to ConcurrentHashMap
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {
                                    // Creating ConcurrentHashMap of even numbers
                                    ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();

                                    // Using put()
                                    evenNumbers.put("Two", 2);
                                    evenNumbers.put("Four", 4);

                                    // Using putIfAbsent()
                                    evenNumbers.putIfAbsent("Six", 6);
                                    System.out.println("ConcurrentHashMap of even numbers: " + evenNumbers);

                                    //Creating ConcurrentHashMap of numbers
                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                                    numbers.put("One", 1);

                                    // Using putAll()
                                    numbers.putAll(evenNumbers);
                                    System.out.println("ConcurrentHashMap of numbers: " + numbers);
                                }
                            }
                        
                    
2. Access ConcurrentHashMap Elements
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {
                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();

                                    numbers.put("One", 1);
                                    numbers.put("Two", 2);
                                    numbers.put("Three", 3);
                                    System.out.println("ConcurrentHashMap: " + numbers);

                                    // Using entrySet()
                                    System.out.println("Key/Value mappings: " + numbers.entrySet());

                                    // Using keySet()
                                    System.out.println("Keys: " + numbers.keySet());

                                    // Using values()
                                    System.out.println("Values: " + numbers.values());

                                    // Using get()
                                    int value1 = numbers.get("Three");
                                    System.out.println("Using get(): " + value1);

                                    // Using getOrDefault()
                                    int value2 = numbers.getOrDefault("Five", 5);
                                    System.out.println("Using getOrDefault(): " + value2);
                                }
                            }
                        
                    
3. Removed ConcurrentHashMap Elements
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {

                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                                    numbers.put("One", 1);
                                    numbers.put("Two", 2);
                                    numbers.put("Three", 3);
                                    System.out.println("ConcurrentHashMap: " + numbers);

                                    // remove method with single parameter
                                    int value = numbers.remove("Two");
                                    System.out.println("Removed value: " + value);

                                    // remove method with two parameters
                                    boolean result = numbers.remove("Three", 3);
                                    System.out.println("Is the entry {Three=3} removed? " + result);

                                    System.out.println("Updated ConcurrentHashMap: " + numbers);
                                }
                            }
                        
                    
Bulk ConcurrentHashMap Operations
  1. 1. forEach() Method
  2. 2. search() Method
  3. 3. reduce() Method
1. forEach() Method
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {

                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                                    numbers.put("One", 1);
                                    numbers.put("Two", 2);
                                    numbers.put("Three", 3);
                                    System.out.println("ConcurrentHashMap: " + numbers);

                                    // forEach() without transformer function
                                    numbers.forEach(4, (k, v) -> System.out.println("key: " + k + " value: " + v));

                                    // forEach() with transformer function
                                    System.out.print("Values are ");
                                    numbers.forEach(4, (k, v) -> v, (v) -> System.out.print(v + ", "));
                                }
                            }
                        
                    
2. search() Method
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {

                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                                    numbers.put("One", 1);
                                    numbers.put("Two", 2);
                                    numbers.put("Three", 3);
                                    System.out.println("ConcurrentHashMap: " + numbers);

                                    // Using search()
                                    String key = numbers.search(4, (k, v) -> {return v == 3 ? k: null;});
                                    System.out.println("Searched value: " + key);

                                }
                            }
                        
                    
3. reduce() Method
                        
                            import java.util.concurrent.ConcurrentHashMap;

                            class Main {
                                public static void main(String[] args) {

                                    ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
                                    numbers.put("One", 1);
                                    numbers.put("Two", 2);
                                    numbers.put("Three", 3);
                                    System.out.println("ConcurrentHashMap: " + numbers);

                                    // Using search()
                                    int sum = numbers.reduce(4, (k, v) -> v, (v1, v2) -> v1 + v2);
                                    System.out.println("Sum of all values: " + sum);

                                }
                            }
                        
                    
ConcurrentHashMap vs HashMap

Here are some of the differences between ConcurrentHashMap and HashMap,

  1. - ConcurrentHashMap is a thread-safe collection. That is, multiple threads can access and modify it at the same time.
  2. - ConcurrentHashMap provides methods for bulk operations like forEach(), search() and reduce().

Why ConcurrentHashMap?

  1. - The ConcurrentHashMap class allows multiple threads to access its entries concurrently.
  2. - By default, the concurrent hashmap is divided into 16 segments. This is the reason why 16 threads are allowed to concurrently modify the map at the same time. However, any number of threads can access the map at a time..
  3. - The putIfAbsent() method will not override the entry in the map if the specified key already exists.
  4. - It provides its own synchronization.