Lab 05: Concurrency & CompletableFuture

Objective

Master Java concurrency: ExecutorService thread pools, CountDownLatch, CompletableFuture pipelines, ConcurrentHashMap, and atomic operations for thread-safe inventory management.

Background

Java concurrency is managed through the java.util.concurrent package. Rather than creating raw Thread objects, modern Java uses ExecutorService to manage thread pools efficiently. CompletableFuture (Java 8+) enables non-blocking async pipelines with composition operators like thenApply, thenCompose, and allOf.

Time

30 minutes

Prerequisites

  • Lab 04 (Exception Handling)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Thread pool, CompletableFuture pipeline, CAS inventory, parallel price fetch, Capstone

💡 compareAndSet (CAS) is the key to lock-free concurrency. Instead of using synchronized, CAS atomically checks whether the current value equals an expected value, and only updates if it does. If another thread modified the value meanwhile, CAS fails — and the while(true) loop retries. This is much faster than locking for low-contention scenarios.

📸 Verified Output:


Summary

API
Use for

Executors.newFixedThreadPool(n)

Bounded thread pool

CountDownLatch(n)

Wait for N tasks to complete

CompletableFuture.supplyAsync

Async computation in pool

thenApply

Transform result (like map)

allOf(...).join()

Wait for all futures

exceptionally

Handle errors in pipeline

ConcurrentHashMap

Thread-safe map

AtomicInteger.compareAndSet

Lock-free CAS update

Further Reading

Last updated