Skip to main content

Lesson 6 of 8

Concurrent Collections & Deadlock Prevention

Regular collections (ArrayList, HashMap) are NOT thread-safe. Java's java.util.concurrent package provides thread-safe alternatives. Understanding deadlock - and how to prevent it - is essential for writing reliable concurrent code.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Concurrent Collections

Concurrent Collections
import java.util.concurrent.*;
import java.util.*;

public class ConcurrentCollections {
    public static void main(String[] args) throws InterruptedException {

        // ConcurrentHashMap - thread-safe HashMap (segment locking)
        // Fine-grained locking: different segments locked independently
        ConcurrentHashMap<String, Book> catalog = new ConcurrentHashMap<>();
        catalog.put("001", new Book("001", "Clean Code", "Martin", 39.99));

        // Atomic operations on ConcurrentHashMap
        catalog.putIfAbsent("001", new Book("001", "duplicate", "x", 0)); // ignored - key exists
        catalog.computeIfAbsent("002", isbn -> loadFromDB(isbn));  // load only if absent
        catalog.merge("003", new Book("003","New","Author",10), (existing, newBook) -> existing); // keep existing

        // CopyOnWriteArrayList - thread-safe list for read-heavy usage
        // Writes create a new copy of the underlying array (expensive)
        // Reads are fast and lock-free - iterators never see concurrent modification
        CopyOnWriteArrayList<String> subscribers = new CopyOnWriteArrayList<>();
        subscribers.add("alice@example.com");
        subscribers.add("bob@example.com");
        // Safe to iterate while another thread adds
        subscribers.forEach(email -> sendEmail(email));

        // BlockingQueue - for producer-consumer pattern
        BlockingQueue<BorrowRequest> requestQueue = new ArrayBlockingQueue<>(100);

        // Producer thread
        new Thread(() -> {
            try {
                requestQueue.put(new BorrowRequest("001", "MBR-01")); // blocks if full
                requestQueue.put(new BorrowRequest("002", "MBR-02"));
            } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        }).start();

        // Consumer thread
        new Thread(() -> {
            try {
                while (true) {
                    BorrowRequest req = requestQueue.take();  // blocks if empty
                    processRequest(req);
                }
            } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        }).start();

        // CountDownLatch - wait for N events before proceeding
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 1; i <= 3; i++) {
            final int id = i;
            new Thread(() -> {
                System.out.println("Module " + id + " loaded");
                latch.countDown();  // decrement
            }).start();
        }
        latch.await();  // blocks until count reaches 0
        System.out.println("All modules loaded - starting application");
    }

    // DEADLOCK PREVENTION:
    // ❌ Thread A holds lock1, waits for lock2
    // ❌ Thread B holds lock2, waits for lock1 → DEADLOCK
    // ✅ Fix: always acquire locks in the SAME ORDER
    static final Object lock1 = new Object();
    static final Object lock2 = new Object();

    // Both methods acquire locks in SAME order (lock1 then lock2)
    static void operationA() {
        synchronized (lock1) { synchronized (lock2) { /*work*/ } }
    }
    static void operationB() {
        synchronized (lock1) { synchronized (lock2) { /*work*/ } }
    }

    static Book loadFromDB(String isbn) { return new Book(isbn, "loaded", "DB", 0); }
    static void sendEmail(String email) { System.out.println("Email sent to: " + email); }
    static void processRequest(BorrowRequest r) { System.out.println("Processing: " + r.isbn()); }
}

record BorrowRequest(String isbn, String memberId) {}

Quick Quiz

Tip

Tip

Practice Concurrent Collections Deadlock Prevention in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Concurrent Collections & Deadlock Prevention

Practice Task

Note

Practice Task - (1) Write a working example of Concurrent Collections Deadlock Prevention from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Concurrent Collections Deadlock Prevention is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done