StackPractices
advanced By Mathias Paulenko

Complete Guide to Java Concurrency

Java concurrency in production: threads, locks, CompletableFuture, virtual threads, executors, collections, memory model, and patterns for high-throughput apps.

Introduction

Java’s concurrency toolkit is the deepest in any mainstream language: synchronized to StampedLock, ExecutorService to CompletableFuture, platform threads to virtual threads (JEP 444). The hard part isn’t the API surface — it’s choosing the right tool for each scenario, because the wrong choice fails the way concurrency bugs always do: silently, under load, after you’ve shipped.

This guide covers the primitives and the patterns around them: threads, pools, locks, futures, virtual threads, collections, atomics, the memory model, and the production decisions (pool sizing, deadlock avoidance, pinning) that determine whether your code survives traffic.

flowchart diagram: subgraph Old[

Thread Fundamentals

Creating Threads

import java.lang.Thread;

// Method 1: Extend Thread
class Worker extends Thread {
    @Override
    public void run() {
        System.out.println("Working in: " + Thread.currentThread().getName());
    }
}
new Worker().start();

// Method 2: Implement Runnable
Thread thread = new Thread(() -> {
    System.out.println("Working in: " + Thread.currentThread().getName());
});
thread.start();

// Method 3: ExecutorService (recommended for production)
import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(8);
executor.submit(() -> {
    System.out.println("Working in: " + Thread.currentThread().getName());
});
executor.shutdown();

Thread Lifecycle

NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED

NEW: Thread created, not started
RUNNABLE: Running or ready to run
BLOCKED: Waiting for a monitor lock
WAITING: Waiting indefinitely for another thread
TIMED_WAITING: Waiting for a specified duration
TERMINATED: Thread completed execution

Thread Properties

Thread thread = new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // Restore interrupt flag
        return;
    }
});

thread.setName("worker-1");
thread.setPriority(Thread.NORM_PRIORITY); // 1-10, default 5
thread.setDaemon(false); // Daemon threads don't prevent JVM shutdown
thread.start();

// Wait for completion
thread.join(5000); // Wait up to 5 seconds
System.out.println("Thread alive: " + thread.isAlive());

ExecutorService

Choosing a Thread Pool

import java.util.concurrent.*;

// Fixed pool: predictable resource usage
ExecutorService fixed = Executors.newFixedThreadPool(8);

// Cached pool: grows on demand, shrinks when idle (60s timeout)
ExecutorService cached = Executors.newCachedThreadPool();

// Single thread: sequential execution with queueing
ExecutorService single = Executors.newSingleThreadExecutor();

// Scheduled: delayed and recurring tasks
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(4);
scheduled.scheduleAtFixedRate(() -> heartbeat(), 0, 10, TimeUnit.SECONDS);
scheduled.scheduleWithFixedDelay(() -> cleanup(), 0, 60, TimeUnit.SECONDS);

// Work stealing: adaptive parallelism (good for ForkJoinTask)
ExecutorService workStealing = Executors.newWorkStealingPool();

Custom Thread Pool with ThreadPoolExecutor

import java.util.concurrent.*;

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    4,                          // Core pool size
    16,                         // Max pool size
    60L, TimeUnit.SECONDS,      // Keep-alive for idle threads
    new LinkedBlockingQueue<>(100),  // Work queue with capacity
    new ThreadFactory() {
        private int count = 0;
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "pool-worker-" + count++);
            t.setDaemon(true);
            return t;
        }
    },
    new ThreadPoolExecutor.CallerRunsPolicy()  // Rejection policy
);

// Rejection policies:
// AbortPolicy: throw RejectedExecutionException (default)
// CallerRunsPolicy: run in the calling thread (backpressure)
// DiscardPolicy: silently discard
// DiscardOldestPolicy: discard oldest queued task

The details that matter: a bounded queue + CallerRunsPolicy is how you get natural backpressure — when the pool saturates, the submitter slows down instead of the queue growing until the JVM dies. The Executors factory methods all ship unbounded queues; for anything user-facing, build the ThreadPoolExecutor yourself.

Graceful Shutdown

ExecutorService executor = Executors.newFixedThreadPool(8);

// Submit tasks
for (int i = 0; i < 100; i++) {
    executor.submit(() -> processItem(i));
}

// Graceful shutdown
executor.shutdown(); // Stop accepting new tasks
try {
    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        executor.shutdownNow(); // Force shutdown
        if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
            System.err.println("Pool did not terminate");
        }
    }
} catch (InterruptedException e) {
    executor.shutdownNow();
    Thread.currentThread().interrupt();
}

Locks

synchronized vs ReentrantLock

// synchronized: simple, JVM-managed, cannot timeout
public synchronized void incrementSync() {
    count++;
}

// ReentrantLock: flexible, can timeout, can be fair
import java.util.concurrent.locks.*;

private final ReentrantLock lock = new ReentrantLock(true); // Fair lock

public void incrementLock() {
    lock.lock();
    try {
        count++;
    } finally {
        lock.unlock(); // MUST be in finally
    }
}

// Try with timeout
public boolean tryIncrement(long timeout, TimeUnit unit) {
    try {
        if (lock.tryLock(timeout, unit)) {
            try {
                count++;
                return true;
            } finally {
                lock.unlock();
            }
        }
        return false; // Could not acquire lock
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    }
}

ReadWriteLock

import java.util.concurrent.locks.*;

private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Map<String, String> cache = new HashMap<>();

public String get(String key) {
    rwLock.readLock().lock();
    try {
        return cache.get(key);
    } finally {
        rwLock.readLock().unlock();
    }
}

public void put(String key, String value) {
    rwLock.writeLock().lock();
    try {
        cache.put(key, value);
    } finally {
        rwLock.writeLock().unlock();
    }
}

StampedLock

import java.util.concurrent.locks.*;

private final StampedLock stampedLock = new StampedLock();
private double x, y;

// Optimistic read: no lock, validate after
public double distanceFromOrigin() {
    long stamp = stampedLock.tryOptimisticRead();
    double currentX = x, currentY = y;
    if (!stampedLock.validate(stamp)) {
        // Optimistic read failed, upgrade to read lock
        stamp = stampedLock.readLock();
        try {
            currentX = x;
            currentY = y;
        } finally {
            stampedLock.unlockRead(stamp);
        }
    }
    return Math.sqrt(currentX * currentX + currentY * currentY);
}

public void move(double deltaX, double deltaY) {
    long stamp = stampedLock.writeLock();
    try {
        x += deltaX;
        y += deltaY;
    } finally {
        stampedLock.unlockWrite(stamp);
    }
}

CompletableFuture

Basic Composition

import java.util.concurrent.*;

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> {
        // Async computation
        return fetchUser(123);
    })
    .thenApply(user -> {
        // Transform result
        return user.getName();
    })
    .thenApply(name -> {
        // Chain another transformation
        return name.toUpperCase();
    })
    .thenAccept(name -> {
        // Consume result (no return)
        System.out.println("Name: " + name);
    })
    .thenRun(() -> {
        // Run after completion
        System.out.println("Done");
    });

future.join(); // Block and get result

Combining Multiple Futures

// Run two futures in parallel and combine results
CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(() -> fetchUser(123));
CompletableFuture<Orders> ordersFuture = CompletableFuture.supplyAsync(() -> fetchOrders(123));

CompletableFuture<UserProfile> profileFuture = userFuture
    .thenCombine(ordersFuture, (user, orders) -> new UserProfile(user, orders));

// Wait for all to complete
CompletableFuture<Void> all = CompletableFuture.allOf(
    CompletableFuture.supplyAsync(() -> fetchUser(1)),
    CompletableFuture.supplyAsync(() -> fetchUser(2)),
    CompletableFuture.supplyAsync(() -> fetchUser(3))
);
all.join();

// Wait for any to complete
CompletableFuture<Object> any = CompletableFuture.anyOf(
    CompletableFuture.supplyAsync(() -> fetchFromPrimary()),
    CompletableFuture.supplyAsync(() -> fetchFromSecondary())
);
Object result = any.join();

Error Handling

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> {
        if (Math.random() > 0.5) {
            throw new RuntimeException("Fetch failed");
        }
        return "success";
    })
    .exceptionally(ex -> {
        // Handle exception, return fallback
        return "fallback";
    })
    .handle((result, ex) -> {
        // Handle both success and exception
        if (ex != null) {
            return "recovered: " + ex.getMessage();
        }
        return result;
    });

// Retry pattern with CompletableFuture
public CompletableFuture<String> fetchWithRetry(String url, int maxRetries) {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> fetch(url));
    for (int i = 0; i < maxRetries; i++) {
        future = future.exceptionallyCompose(ex -> {
            System.err.println("Retry " + (i + 1) + ": " + ex.getMessage());
            return CompletableFuture.supplyAsync(() -> fetch(url));
        });
    }
    return future;
}

Timeout Handling

import java.util.concurrent.*;

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> slowFetch())
    .orTimeout(5, TimeUnit.SECONDS) // Timeout after 5s (Java 9+)
    .exceptionally(ex -> {
        if (ex instanceof TimeoutException) {
            return "timeout fallback";
        }
        return "error fallback";
    });

// Complete with default value after timeout
CompletableFuture<String> withDefault = CompletableFuture
    .supplyAsync(() -> slowFetch())
    .completeOnTimeout("default", 5, TimeUnit.SECONDS);

Virtual Threads (Java 21+)

Virtual threads are lightweight threads managed by the JVM, not the OS. Millions of them can run on a few carrier platform threads.

import java.util.concurrent.*;

// Create a virtual thread
Thread vt = Thread.ofVirtual().start(() -> {
    System.out.println("Running in virtual thread");
});

// Virtual thread per task executor
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<String>> futures = new ArrayList<>();
    
    for (int i = 0; i < 10_000; i++) {
        final int id = i;
        futures.add(executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1)); // Blocking call is fine!
            return "Result " + id;
        }));
    }
    
    // All 10,000 tasks complete in ~1 second
    for (Future<String> f : futures) {
        System.out.println(f.get());
    }
}

// Structured concurrency (JEP 525 — finalized in Java 25)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Subtask<User> user = scope.fork(() -> fetchUser(123));
    Subtask<Orders> orders = scope.fork(() -> fetchOrders(123));
    
    scope.join();           // Wait for all
    scope.throwIfFailed();  // Propagate exception if any failed
    
    UserProfile profile = new UserProfile(user.get(), orders.get());
}

When to Use Virtual Threads

Use virtual threads when:
- I/O-bound work (HTTP calls, database queries, file I/O)
- High number of concurrent tasks (thousands to millions)
- You want simple blocking-code style without callbacks

Do NOT use virtual threads when:
- CPU-bound work (use platform threads or ForkJoinPool)
- Pinning-sensitive operations (synchronized blocks pin carriers)
- Thread-local variables are heavily used (each virtual thread has its own)

Two rules teams learn the hard way: don’t pool virtual threads — newVirtualThreadPerTaskExecutor is cheap, and pooling defeats the design. And don’t reach for virtual threads to speed up a slow task — they trade single-task latency for throughput, not speed. Compare with Go concurrency if you’re evaluating the model across languages.

Concurrent Collections

import java.util.concurrent.*;
import java.util.*;

// ConcurrentHashMap: thread-safe HashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
map.computeIfAbsent("key", k -> expensiveCompute(k));
map.merge("counter", 1, Integer::sum); // Atomic increment

// CopyOnWriteArrayList: thread-safe List, copies on write
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item"); // Creates a new copy

// ConcurrentLinkedQueue: non-blocking queue
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.offer("item");
String item = queue.poll();

// BlockingQueue: producer-consumer pattern
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(100);
blockingQueue.put("item");  // Blocks if full
String item = blockingQueue.take();  // Blocks if empty

// ArrayBlockingQueue: bounded, array-backed
BlockingQueue<String> bounded = new ArrayBlockingQueue<>(1000);

// DelayQueue: elements become available after a delay
class DelayedTask implements Delayed {
    private final long startTime;
    private final String name;
    
    public DelayedTask(String name, long delayMs) {
        this.name = name;
        this.startTime = System.currentTimeMillis() + delayMs;
    }
    
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
    
    @Override
    public int compareTo(Delayed o) {
        return Long.compare(startTime, ((DelayedTask) o).startTime);
    }
}

CopyOnWriteArrayList is the one to be suspicious of: every mutation copies the array, so it’s right for read-heavy, write-rarely data (listener lists, config snapshots) and wrong for anything else.

Atomic Variables

import java.util.concurrent.atomic.*;

AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();     // ++i
counter.getAndIncrement();     // i++
counter.compareAndSet(0, 1);   // CAS: if 0, set to 1
counter.updateAndGet(x -> x * 2); // Atomic update

AtomicLong longCounter = new AtomicLong(0);
AtomicBoolean flag = new AtomicBoolean(false);
AtomicReference<String> ref = new AtomicReference<>("initial");

// LongAdder: better for high-contention counters
LongAdder adder = new LongAdder();
adder.increment();
adder.add(10);
long sum = adder.sum(); // Not atomic, but fast for counting

// LongAccumulator: custom accumulation function
LongAccumulator max = new LongAccumulator(Long::max, Long.MIN_VALUE);
max.accumulate(42);
max.accumulate(17);
long result = max.get(); // 42

Java Memory Model

Happens-Before Relationship

// The happens-before relationship guarantees visibility:
// 1. Thread A writes to a volatile variable
// 2. Thread B reads the same volatile variable
// → Everything A did before the write is visible to B

private volatile boolean running = true;

public void stop() {
    running = false; // Write to volatile — visible to other threads
}

public void run() {
    while (running) { // Read volatile — sees the latest value
        doWork();
    }
}

Safe Publication

// Unsafe: another thread might see partially constructed object
private SomeObject instance; // NOT volatile

// Safe: volatile ensures safe publication
private volatile SomeObject instance;

// Safe: final fields are visible after construction
class ImmutableValue {
    private final int x;
    private final int y;
    
    public ImmutableValue(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

// Safe: synchronized block establishes happens-before
private SomeObject instance;
private final Object lock = new Object();

public SomeObject getInstance() {
    synchronized (lock) {
        if (instance == null) {
            instance = new SomeObject();
        }
        return instance;
    }
}

The rule that covers most of it: shared mutable state needs a happens-before edge (volatile, synchronized, atomic, or final-fields-safe publication). If you can’t point at the edge, you don’t have one — and the JVM is allowed to cache the old value indefinitely.

One edge case that keeps showing up in reviews: volatile fixes visibility, not atomicity. counter++ on a volatile int is still read-modify-write — two threads can increment once between them. volatile is for flags and publication; for compound operations you want AtomicInteger or a lock.

Production Patterns

The API surface is the easy half. These are the decisions that break in production:

Thread Pool Sizing

N_cpu * (1 + W/C) — cores times (1 + wait/compute ratio) — is the starting formula, not the answer. Measure the real W/C under load; a pool sized for W/C=10 on tasks that actually block 100× saturates the queue at 10% of expected throughput. For an SLO-driven approach, see the thread pool sizing template.

Deadlock Avoidance

  • Lock ordering: always acquire locks in a global order (by object identity or name) — lock ordering is the only strategy that provably kills cyclic waits.
  • tryLock with timeout: gives you a way out when ordering is impossible.
  • jstack / Thread.dumpStack() in staging: reproduce a deadlock once and you’ll never ship unordered locks again. jcmd <pid> Thread.print does the same on modern JDKs.

Backpressure

An unbounded queue is a memory leak with extra steps. LinkedBlockingQueue(100) + CallerRunsPolicy turns “queue grows until OOM” into “callers slow down.” If you’d rather drop than block, AbortPolicy + a circuit breaker upstream is the honest version.

Virtual Thread Pinning

synchronized inside a virtual thread pins it to its carrier — 10,000 virtual threads and 8 carriers pinned at once is a thread starvation bug wearing a modern costume. Swap synchronized for ReentrantLock on paths virtual threads hit, or audit -Djdk.tracePinnedThreads output before rollout.

Circuit Breaker with CompletableFuture

class CircuitBreaker {
    private final AtomicReference<State> state = new AtomicReference<>(State.CLOSED);
    private final AtomicInteger failureCount = new AtomicInteger(0);
    private final int threshold;
    private final long timeoutMs;
    private volatile long lastFailureTime;

    enum State { CLOSED, OPEN, HALF_OPEN }

    public <T> CompletableFuture<T> execute(java.util.function.Supplier<T> supplier) {
        if (state.get() == State.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > timeoutMs) {
                state.set(State.HALF_OPEN);
            } else {
                return CompletableFuture.failedFuture(new RuntimeException("Circuit open"));
            }
        }
        return CompletableFuture.supplyAsync(supplier)
            .handle((result, ex) -> {
                if (ex != null) {
                    if (failureCount.incrementAndGet() >= threshold) {
                        state.set(State.OPEN);
                        lastFailureTime = System.currentTimeMillis();
                    }
                    throw new CompletionException(ex);
                }
                failureCount.set(0);
                return CompletableFuture.completedFuture(result);
            }).thenCompose(f -> f);
    }
}

Testing Concurrent Code

import org.junit.jupiter.api.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

@Test
void testConcurrentIncrement() throws Exception {
    AtomicInteger counter = new AtomicInteger(0);
    int threads = 100;
    int incrementsPerThread = 1000;
    
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    CountDownLatch latch = new CountDownLatch(threads);
    
    for (int i = 0; i < threads; i++) {
        executor.submit(() -> {
            for (int j = 0; j < incrementsPerThread; j++) {
                counter.incrementAndGet();
            }
            latch.countDown();
        });
    }
    
    latch.await(10, TimeUnit.SECONDS);
    executor.shutdown();
    
    assertEquals(threads * incrementsPerThread, counter.get());
}

@Test
void testCompletableFuture() throws Exception {
    CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello")
        .thenApply(String::toUpperCase)
        .thenApply(s -> s + " world");
    
    assertEquals("HELLO world", future.get(5, TimeUnit.SECONDS));
}

Test concurrency properties, not scheduling: invariants under contention (latch + executor, as above), cancellation semantics, and timeouts. A test that asserts ordering on a BlockingQueue is testing your implementation, not a race.

Best Practices

  • ExecutorService over raw threads. Pool lifecycle is the hard part; let Executors/ThreadPoolExecutor own it.
  • Virtual threads for I/O, platform threads for CPU. Match the scheduler to the workload, not the other way around.
  • ReentrantLock on virtual-thread paths. synchronized pins carriers.
  • Bounded queues + CallerRunsPolicy. Backpressure beats OOM.
  • Restore interrupt() flags. Swallowed interrupts break cancellation everywhere downstream.

Common Mistakes

  • Pooling virtual threads. newVirtualThreadPerTaskExecutor is meant to be cheap — pooling it brings back the constraint it exists to remove.
  • synchronized inside virtual-thread-heavy code. Pinning under load is the #1 virtual-thread production incident.
  • Unbounded LinkedBlockingQueue (the Executors default). The queue grows until the JVM dies.
  • Swallowing InterruptedException. Catch → interrupt() → return; never catch-and-ignore.
  • Atomics without a happens-before edge. AtomicInteger alone doesn’t publish the surrounding state — pair it with volatile/final or you’re still racing.

Production Checklist

Runnable versions of these patterns ship in the companion repository: bounded executor, circuit breaker, and contention tests.

  • All pools ThreadPoolExecutor with bounded queue + named threads
  • shutdown()/awaitTermination() tested on app stop
  • synchronized audited on virtual-thread paths (pinning)
  • Lock ordering documented wherever multiple locks coexist
  • Thread-locals reviewed before enabling virtual threads
  • InterruptedException never swallowed
  • Concurrency tests assert invariants, not scheduling
  • -Djdk.tracePinnedThreads checked in staging rollout

See Also

Frequently Asked Questions

Should I use virtual threads or platform threads?

Virtual threads for I/O-bound work with high concurrency (thousands of HTTP calls, DB queries); platform threads for CPU-bound work or fine-grained scheduling control. Virtual threads aren't faster per task — they fit more concurrent tasks on fewer OS threads.

What is the difference between thenApply and thenCompose?

thenApply takes a sync function and wraps the result; thenCompose takes a function that returns a CompletableFuture and flattens it (like flatMap). Use thenCompose when the next step is itself async.

How do I choose between synchronized and ReentrantLock?

synchronized for simple cases (the JVM optimizes it well); ReentrantLock when you need tryLock timeout, fairness, interruptibility, or virtual-thread pinning safety. synchronized is always reentrant and cannot timeout.

What is thread pinning in virtual threads?

Virtual threads pin to their carrier inside synchronized blocks or native methods — while pinned, the carrier can't run other virtuals. Use ReentrantLock in hot paths with virtual threads.

How do I handle InterruptedException?

Catch it, restore with Thread.currentThread().interrupt(), exit gracefully — or rethrow. Never swallow it; that breaks cooperative cancellation everywhere downstream.

What is structured concurrency?

StructuredTaskScope (JEP 525, finalized in Java 25): child tasks live inside a scope, so join() waits for all and throwIfFailed() propagates the first error — the parent owns the children's lifecycle, and nothing leaks on failure.

What is the best thread pool size?

N_cpu * (1 + W/C) as a starting point; measure real wait/compute ratio under load — the formula is only as good as your W/C estimate.