Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java ConcurrentHashMap: Operations, Examples, and Best Practices

Java ConcurrentHashMap

Explore the Java ConcurrentHashMap class, learn how to create and manipulate it, and discover its key advantages with practical code examples.

The ConcurrentHashMap class from the Java collections framework offers a thread‑safe map implementation. Multiple threads can read and write concurrently without corrupting the map’s integrity.

It implements the ConcurrentMap interface and is part of java.util.concurrent.

Mastering Java ConcurrentHashMap: Operations, Examples, and Best Practices

Create a ConcurrentHashMap

First, import the class:

import java.util.concurrent.ConcurrentHashMap;

Then instantiate it. You can specify an initial capacity and load factor, or rely on the defaults.

// Capacity 8, load factor 0.6
ConcurrentHashMap<Key, Value> numbers = new ConcurrentHashMap<>(8, 0.6f);

Parameters

Default constructor creates a map with a capacity of 16 and a load factor of 0.75:

ConcurrentHashMap<Key, Value> numbers1 = new ConcurrentHashMap<>();

Creating ConcurrentHashMap from Existing Maps

You can populate a new ConcurrentHashMap with the entries of any other map.

import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> evenNumbers = new HashMap<>();
        evenNumbers.put("Two", 2);
        evenNumbers.put("Four", 4);
        System.out.println("HashMap: " + evenNumbers);

        ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>(evenNumbers);
        numbers.put("Three", 3);
        System.out.println("ConcurrentHashMap: " + numbers);
    }
}

Output

HashMap: {Four=4, Two=2}
ConcurrentHashMap: {Four=4, Two=2, Three=3}

Key Methods of ConcurrentHashMap

Inserting Elements

ConcurrentHashMap<String, Integer> evenNumbers = new ConcurrentHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);

evenNumbers.putIfAbsent("Six", 6);
System.out.println("Even numbers: " + evenNumbers);

ConcurrentHashMap<String, Integer> numbers = new ConcurrentHashMap<>();
numbers.put("One", 1);
numbers.putAll(evenNumbers);
System.out.println("Numbers: " + numbers);

Output

Even numbers: {Six=6, Four=4, Two=2}
Numbers: {Six=6, One=1, Four=4, Two=2}

Accessing Elements

Use view collections or key/value retrieval methods.

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

System.out.println("Map: " + numbers);
System.out.println("Entries: " + numbers.entrySet());
System.out.println("Keys: " + numbers.keySet());
System.out.println("Values: " + numbers.values());

int val = numbers.get("Three");
System.out.println("get(\"Three\"): " + val);
int def = numbers.getOrDefault("Five", 5);
System.out.println("getOrDefault(\"Five\", 5): " + def);

Output

Map: {One=1, Two=2, Three=3}
Entries: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]
get("Three"): 3
getOrDefault("Five", 5): 5

Removing Entries

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

int removed = numbers.remove("Two");
System.out.println("Removed value: " + removed);
boolean deleted = numbers.remove("Three", 3);
System.out.println("Entry {Three=3} removed? " + deleted);
System.out.println("Updated map: " + numbers);

Output

Removed value: 2
Entry {Three=3} removed? true
Updated map: {One=1}

Bulk Operations

These methods leverage parallelism to process large maps efficiently.

forEach()

Iterates over entries, optionally in parallel, and applies a consumer.

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

Here 4 is the parallel threshold – when the map has at least 4 elements, the operation may run concurrently.

search()

Finds an entry that satisfies a predicate. Returns the first match.

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

reduce()

Aggregates values using a reducer. Useful for sums, products, or custom accumulations.

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

ConcurrentHashMap vs. HashMap

Why Use ConcurrentHashMap?


Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  3. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  4. Java List Interface: Overview, Implementations, and Key Methods
  5. Java TreeMap: Master Sorted Maps with Practical Examples
  6. Java HashSet Class: Complete Guide to Operations, Methods, and Set Theory
  7. Mastering Java TreeSet: Operations, Methods, and Practical Examples
  8. Mastering Java Collection Algorithms: Sorting, Shuffling, and More
  9. Generate Random Numbers in Java: Practical Guide with Random and Math.random
  10. Java Numbers Class – Wrapper Classes & Inheritance Explained