Skip to main content

Lesson 7 of 8

Mini Project: Library System - Part 9 (Concurrent Checkout)

Make the Library System concurrent - ConcurrentHashMap for the catalog, CopyOnWriteArrayList for the reservation list, BlockingQueue for the checkout request queue, and CompletableFuture for async notifications.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Thread-Safe Library Service

Thread-Safe Library Service
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.*;

public class ConcurrentLibraryService {
    private final ConcurrentHashMap<String, Book> catalog    = new ConcurrentHashMap<>();
    private final BlockingQueue<BorrowRequest> checkoutQueue = new LinkedBlockingQueue<>(500);
    private final AtomicLong transactionCount                = new AtomicLong(0);
    private final ExecutorService workers                    = Executors.newFixedThreadPool(4);
    private volatile boolean running                         = true;

    public void start() {
        // Worker threads consuming requests from the queue
        for (int i = 0; i < 4; i++) {
            workers.submit(this::processRequests);
        }
    }

    private void processRequests() {
        while (running || !checkoutQueue.isEmpty()) {
            try {
                BorrowRequest req = checkoutQueue.poll(1, TimeUnit.SECONDS);
                if (req == null) continue;
                processCheckout(req);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }

    private void processCheckout(BorrowRequest req) {
        Book book = catalog.get(req.isbn());
        if (book == null) {
            System.err.printf("[%s] Book not found: %s%n", Thread.currentThread().getName(), req.isbn());
            return;
        }
        // Atomic borrow - synchronized on specific book (fine-grained)
        synchronized (book) {
            if (!book.isAvailable()) {
                System.err.printf("[%s] Unavailable: %s%n", Thread.currentThread().getName(), req.isbn());
                return;
            }
            book.borrow();
        }
        long txId = transactionCount.incrementAndGet();
        System.out.printf("[TX-%d] %s → %s (thread: %s)%n",
            txId, req.memberId(), book.getTitle(), Thread.currentThread().getName());

        // Async: send confirmation email without blocking checkout flow
        CompletableFuture.runAsync(() -> sendConfirmation(req.memberId(), book.getTitle()));
    }

    public boolean submitCheckout(BorrowRequest request) {
        return checkoutQueue.offer(request);  // non-blocking; returns false if full
    }

    public void addBook(Book book) {
        catalog.put(book.getIsbn(), book);
    }

    public void shutdown() throws InterruptedException {
        running = false;
        workers.shutdown();
        workers.awaitTermination(5, TimeUnit.SECONDS);
        System.out.printf("Service shutdown. Total transactions: %d%n", transactionCount.get());
    }

    private void sendConfirmation(String memberId, String title) {
        System.out.printf("📧 Confirmation sent to %s for '%s'%n", memberId, title);
    }

    public static void main(String[] args) throws Exception {
        ConcurrentLibraryService service = new ConcurrentLibraryService();
        service.addBook(new Book("001", "Clean Code", "Martin", 39.99));
        service.addBook(new Book("002", "Effective Java", "Bloch", 44.99));
        service.start();

        // Simulate concurrent requests from multiple members
        for (int i = 1; i <= 10; i++) {
            final int memberId = i;
            new Thread(() -> {
                service.submitCheckout(new BorrowRequest("001", "MBR-" + memberId));
            }).start();
        }

        Thread.sleep(2000);
        service.shutdown();
    }
}

Quick Quiz

Tip

Tip

Practice Mini Project Library System Part 9 Concurrent Checkout 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 Mini Project: Library System - Part 9 (Concurrent Checkout)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Library System Part 9 Concurrent Checkout 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 Mini Project Library System Part 9 Concurrent Checkout 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