The Java Concurrency API: Executors, CompletableFuture, Locks and Concurrent Collections

Practical java.util.concurrent: threads vs tasks, ExecutorService and thread-pool sizing, Future and CompletableFuture composition and error handling, locks (synchronized, ReentrantLock, ReadWriteLock, StampedLock), atomics and LongAdder, synchronizers, concurrent collections and BlockingQueue, and how they relate to virtual threads.

On this page

Simple definition#

java.util.concurrent provides higher-level building blocks for running work in parallel and coordinating threads safely:

  • executors run tasks
  • futures represent results that arrive later
  • locks and atomics protect shared state
  • concurrent collections are safe to share between threads.

The problem#

Creating raw Threads per task does not scale (platform threads are expensive OS threads). Hand-written wait/notify code is notoriously buggy. Sharing a plain HashMap between threads corrupts it. The concurrency API gives tested abstractions, so you rarely touch low-level primitives.

Executors: separate tasks from threads#

try (ExecutorService pool = Executors.newFixedThreadPool(8)) {        // AutoCloseable since Java 19
    Future<Price> price = pool.submit(() -> pricing.quote(sku));
    Future<Stock> stock = pool.submit(() -> inventory.check(sku));
    return new Offer(price.get(2, SECONDS), stock.get(2, SECONDS));
}   // close() waits for tasks and shuts the pool down
FactoryBehaviourUse for
newFixedThreadPool(n)n threads, unbounded queueCPU-bound work (n ≈ cores)
newCachedThreadPool()Grows without limitRarely; prefer bounded pools
newScheduledThreadPool(n)Delayed and periodic tasksTimers, polling
newWorkStealingPool() / ForkJoinPoolWork stealingRecursive divide and conquer, parallel streams
newVirtualThreadPerTaskExecutor() (21)One cheap virtual thread per taskBlocking I/O-bound work
new ThreadPoolExecutor(...)Full control: core and max size, bounded queue, rejection policyProduction services

Sizing platform-thread pools:

  • CPU-bound: about cores (or cores + 1).
  • I/O-bound: cores × (1 + wait time / compute time), which often means virtual threads instead.
  • Always use a bounded queue and a rejection policy (for example CallerRunsPolicy) to get backpressure instead of running out of memory.
  • Name your threads with a ThreadFactory for readable thread dumps.

CompletableFuture: composing async work#

CompletableFuture<Offer> offer =
    CompletableFuture.supplyAsync(() -> pricing.quote(sku), ioPool)            // run async
        .thenCombine(CompletableFuture.supplyAsync(() -> inventory.check(sku), ioPool),
                     Offer::new)                                              // join two results
        .thenCompose(o -> CompletableFuture.supplyAsync(() -> promo.apply(o), ioPool)) // chain async step
        .orTimeout(2, SECONDS)                                                // fail if too slow
        .exceptionally(ex -> Offer.unavailable(sku));                         // fallback
MethodPurpose
supplyAsync / runAsyncStart async work (always pass an executor; the default is the common ForkJoinPool)
thenApplyTransform the result (like map)
thenComposeChain another async call (like flatMap)
thenCombineCombine two independent futures
allOf / anyOfWait for all, or the first
exceptionally / handle / whenCompleteRecover, transform or observe errors
orTimeout / completeOnTimeoutTime limits (Java 9+)

Exceptions inside stages are wrapped in CompletionException. join() throws unchecked exceptions; get() throws the checked ExecutionException.

Locks#

MechanismFeaturesUse when
synchronizedSimple, reentrant, auto-release; no longer pins virtual threads since Java 24 (JEP 491)Default for short critical sections
ReentrantLocktryLock(timeout), interruptible locking, fairness, multiple ConditionsYou need timeouts or try-lock
ReentrantReadWriteLockMany readers or one writerRead-heavy shared data
StampedLockOptimistic reads (no locking, then validate); not reentrantVery read-heavy hot paths, used with care
private final ReentrantLock lock = new ReentrantLock();
void transfer(Account a, Account b, BigDecimal amt) throws InterruptedException {
    if (lock.tryLock(100, MILLISECONDS)) {
        try { a.debit(amt); b.credit(amt); }
        finally { lock.unlock(); }                        // always in finally
    } else throw new BusyException();
}

Avoid deadlocks: acquire multiple locks in a global order, keep critical sections short, never call unknown code (callbacks, I/O) while holding a lock, and prefer tryLock with timeouts.

Atomics#

AtomicInteger, AtomicLong and AtomicReference use hardware compare-and-set (CAS), which is lock-free:

counter.incrementAndGet();
ref.updateAndGet(cfg -> cfg.withLimit(100));                  // retried CAS loop

Under high contention, LongAdder (striped counters) beats AtomicLong for counters and metrics. VarHandle gives low-level atomic access to fields and array elements.

Synchronizers#

ClassWhat it coordinates
CountDownLatchWait until N events happen (one-shot)
CyclicBarrierN threads wait for each other, repeatedly
SemaphoreLimit concurrent access to N permits (for example a connection limit)
PhaserFlexible multi-phase barriers
ExchangerTwo threads swap objects

Concurrent collections#

CollectionHow it worksUse for
ConcurrentHashMapCAS on empty bins, a lock per bin otherwise; lock-free readsShared caches and registries. Use atomic methods: computeIfAbsent, merge.
CopyOnWriteArrayListCopies the array on every writeListener lists: many reads, rare writes
ConcurrentLinkedQueue / DequeLock-free linked structuresNon-blocking queues
LinkedBlockingQueue, ArrayBlockingQueueBlocking put and takeProducer–consumer with backpressure
ConcurrentSkipListMapLock-free sorted mapConcurrent sorted data
// Atomic, race-free "get or create"
Session s = sessions.computeIfAbsent(userId, id -> new Session(id));
// Race-free counting
hits.merge(path, 1L, Long::sum);

How it fits together#

Choosing a concurrency tool
flowchart TB
    Q{"What kind of work?"} -->|"blocking I/O, many tasks"| VT["Virtual threads<br/>(+ structured concurrency)"]
    Q -->|"CPU-bound"| FJ["Fixed pool ≈ cores / ForkJoinPool"]
    Q -->|"async pipelines, callbacks"| CF["CompletableFuture / Reactor"]
    S{"Shared state?"} -->|"counter"| AT["AtomicLong / LongAdder"]
    S -->|"map / queue"| CC["ConcurrentHashMap / BlockingQueue"]
    S -->|"compound invariant"| LK["synchronized / ReentrantLock"]
    S -->|"none (immutable)"| IM["Best: share immutable data"]

Common mistakes#

Quick check#

Why use an ExecutorService instead of new Thread()? It reuses threads, bounds concurrency, queues work, returns futures and centralises shutdown and error handling.

thenApply vs thenCompose? thenApply transforms the result synchronously (map). thenCompose chains another asynchronous step that returns a CompletableFuture (flatMap).

When choose ReentrantLock over synchronized? When you need tryLock with a timeout, interruptible locking, fairness or multiple conditions.

Why is LongAdder faster than AtomicLong under contention? It spreads updates across several cells, so threads rarely compete for the same CAS, and sums the cells when read.

How do you avoid deadlocks? Acquire locks in a consistent global order, hold them briefly, avoid calling external code while holding them, and use timeouts.

What is the safe way to “get or create” in a ConcurrentHashMap? computeIfAbsent, which performs the check and the insert atomically.

Summary#

  • Submit tasks to executors; bound pools and queues; name threads.
  • Compose async work with CompletableFuture, always with an explicit executor and error handling.
  • Prefer immutability, then atomics and concurrent collections, then locks.
  • For blocking I/O on Java 21+, virtual threads usually beat complex async code.

References#