Implementing a Concurrent Inventory System Using ConcurrentHashMap

Implementing a Concurrent Inventory System Using ConcurrentHashMap

Welcome back! In previous lessons, you've learned about advanced data-sharing concepts and synchronization techniques. Today, we will expand on those foundations by delving into implementing a concurrent inventory system using ConcurrentHashMap. This lesson will help you understand how to build thread-safe applications, a crucial skill in Java multi-threaded programming.

What You'll Learn

In this lesson, you'll gain the ability to:

  • Utilize ConcurrentHashMap for managing data in a multi-threaded environment.
  • Perform atomic operations to safely manipulate shared data.
  • Implement thread-safe inventory systems where multiple threads can modify data concurrently without conflicts.

By the end of this lesson, you will have the skills to manage shared data in multi-threaded systems without relying on locks, increasing efficiency and safety.

Building the Inventory System

Let's start by looking at the InventorySystem class, which manages the inventory of items.

import java.util.concurrent.ConcurrentHashMap;

public class InventorySystem {
    private ConcurrentHashMap<String, Integer> inventory = new ConcurrentHashMap<>();
    
    // Adding an item to the inventory with atomic operations
    public void addItem(String item, int quantity) {
        inventory.merge(item, quantity, Integer::sum);
    }

    // Removing an item from the inventory while ensuring quantities stay valid
    public void removeItem(String item, int quantity) {
        inventory.computeIfPresent(item, (key, val) -> val - quantity > 0 ? val - quantity : null);
    }

    // Retrieving the current quantity of a specific item
    public int getQuantity(String item) {
        return inventory.getOrDefault(item, 0);
    }

    // Displaying all items and their quantities
    public void displayInventory() {
        inventory.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Let's go through each method in detail.

addItem()

The addItem() method uses the merge function to ensure atomic updates. This method either adds a new item to the inventory or updates an existing one by adding the given quantity. The operation is thread-safe, which means multiple threads can modify the inventory concurrently without causing conflicts.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal