Java ConcurrentHashMap putIfAbsent() Method

The ConcurrentHashMap.putIfAbsent() method in Java is used to insert a key-value pair into a ConcurrentHashMap only if the key is not already present in the map. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality. We will also cover a real-world use case to show how ConcurrentHashMap can be used effectively in a concurrent environment.

Table of Contents

  1. Introduction
  2. putIfAbsent Method Syntax
  3. Examples
    • Adding Entries to a ConcurrentHashMap
    • Handling Existing Keys
  4. Real-World Use Case
    • Example: Managing a Student Registration System
  5. Conclusion

Introduction

The ConcurrentHashMap.putIfAbsent() method is a member of the ConcurrentHashMap class in Java. It allows you to insert a key-value pair into the map only if the key is not already associated with a value. The ConcurrentHashMap class is part of the java.util.concurrent package, designed for high concurrency and scalability.

putIfAbsent() Method Syntax

The syntax for the putIfAbsent method is as follows:

public V putIfAbsent(K key, V value)
  • The method takes two parameters:
    • key of type K, which represents the key to be inserted.
    • value of type V, which represents the value to be associated with the key.
  • The method returns the current value associated with the specified key, or null if there was no mapping for the key.

Examples

Adding Entries to a ConcurrentHashMap

The putIfAbsent method can be used to add key-value pairs to a ConcurrentHashMap only if the key is not already present.

Example

import java.util.concurrent.ConcurrentHashMap;

public class PutIfAbsentExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap with String keys and Integer values
        ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();

        // Adding entries to the ConcurrentHashMap
        people.putIfAbsent("Ravi", 25);
        people.putIfAbsent("Priya", 30);
        people.putIfAbsent("Vijay", 35);

        // Printing the ConcurrentHashMap
        System.out.println("ConcurrentHashMap: " + people);
    }
}

Output:

ConcurrentHashMap: {Ravi=25, Priya=30, Vijay=35}

Handling Existing Keys

The putIfAbsent method returns the current value associated with the specified key if the key is already present in the ConcurrentHashMap.

Example

import java.util.concurrent.ConcurrentHashMap;

public class ExistingKeyExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap with String keys and Integer values
        ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();

        // Adding entries to the ConcurrentHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);

        // Trying to add a new value for an existing key
        Integer existingValue = people.putIfAbsent("Ravi", 40);

        // Printing the results
        System.out.println("Existing value for 'Ravi': " + existingValue);
        System.out.println("ConcurrentHashMap: " + people);
    }
}

Output:

Existing value for 'Ravi': 25
ConcurrentHashMap: {Ravi=25, Priya=30}

Real-World Use Case

Example: Managing a Student Registration System

A common real-world use case for ConcurrentHashMap is managing a student registration system where each student can register only once.

Example

import java.util.concurrent.ConcurrentHashMap;

public class StudentRegistration {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap to manage student registrations
        ConcurrentHashMap<String, String> studentRegistrations = new ConcurrentHashMap<>();

        // Adding student registrations to the ConcurrentHashMap
        studentRegistrations.putIfAbsent("Ravi", "Registered");
        studentRegistrations.putIfAbsent("Priya", "Registered");
        studentRegistrations.putIfAbsent("Vijay", "Registered");

        // Attempting to register a student who is already registered
        String registrationStatus = studentRegistrations.putIfAbsent("Ravi", "Already Registered");

        // Printing the results
        System.out.println("Registration status for 'Ravi': " + registrationStatus);
        System.out.println("Student Registrations: " + studentRegistrations);
    }
}

Output:

Registration status for 'Ravi': Registered
Student Registrations: {Ravi=Registered, Priya=Registered, Vijay=Registered}

In this example, ConcurrentHashMap is used to manage student registrations, ensuring that each student can register only once using the putIfAbsent method.

Conclusion

The ConcurrentHashMap.putIfAbsent() method in Java provides a way to insert key-value pairs into a ConcurrentHashMap only if the key is not already present, in a thread-safe manner. By understanding how to use this method, you can efficiently manage collections of key-value pairs in your Java applications, especially in concurrent environments. The method allows you to handle conditional insertions, making it a versatile tool for data management in multi-threaded scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top