Skip to content
Commitwise
Menu
Java Backend

Java concurrency: memory model, locks and executors

Why count++ loses updates and a stop flag can be ignored forever, when to use volatile, synchronized, locks, atomics and ConcurrentHashMap, and how to run work with ExecutorService and CompletableFuture without exhausting threads, the java.util.concurrent questions of every Java interview.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A view counter that’s always a little low. A background job that ignores the “stop” button. A service that runs fine for weeks, then freezes with every thread waiting on another. Each of these comes from code that’s correct on one thread and wrong on many.

Virtual threads and coroutines changed how we wait, but not what happens when two threads touch the same data. That part, the Java Memory Model, locks and java.util.concurrent, is still what interviewers ask about in a Java backend interview. The Concurrency lesson compares async models across languages; this one goes deep into the JVM.

New to some of these? Open what you need, or skip ahead.

Basics:What is a thread?

A thread is one line of execution inside a program. A server runs many at once: each request gets one, so a slow request doesn’t hold up the others. Threads of one program share the same memory, which is what makes them fast to communicate and easy to get wrong.

Basics:What is a race condition?

A race condition is a bug where the result depends on the timing of threads: run the same code twice and get different answers. It usually happens when two threads read and change the same data at the same time. Races hide in tests, which rarely run things truly in parallel, and show up under production load.

Part Not started

What one thread sees of another

Two problems hide in shared data:

  • Lost updates. count++ looks like one step but is three: read count, add one, write it back. If two threads read 41 at the same moment, both write 42, and one view is lost.
  • Invisible writes. For speed, each CPU core keeps copies of memory in its caches, and the JIT compiler may keep a variable in a register or reorder instructions. Without a rule that forces it, a thread may never see another thread’s write.

Java gives you three tools, from lightest to heaviest:

ToolFixesUse for
volatilevisibilitya flag or a reference that one thread writes and others read
AtomicInteger, AtomicLong, LongAddervisibility and atomic updates of one valuecounters, sequence numbers
synchronized or a Lockvisibility and atomicity of a whole blockseveral values that must change together

The Java Memory Model (JLS chapter 17) defines which writes a read may see. Without synchronization, the compiler, JIT and CPU may reorder and cache freely, so the only guarantees come from happens-before edges: program order within a thread, unlocking a monitor before every later lock of it, a write to a volatile field before every later read of it, Thread.start() before the started thread’s actions, a thread’s actions before another thread’s successful join(), and the java.util.concurrent hand-offs (putting into a BlockingQueue before taking out, completing a Future before get() returns). Happens-before is transitive, which is what makes “write data, then write a volatile flag; read the flag, then read data” safe. volatile gives visibility and ordering but not atomicity of compound actions; atomics add CAS-based read-modify-write; locks give mutual exclusion plus visibility for everything inside. final fields are guaranteed visible after construction if this doesn’t escape the constructor. Interviewers probe exactly these: the stop-flag bug, count++, double-checked locking, and when LongAdder beats AtomicLong.

Predict the output

Two threads each run count++ 100,000 times on a shared int field, and the main thread joins both. What does it print?

var count = 0

fun main() {
    val work = Runnable { repeat(100_000) { count++ } }
    val a = Thread(work)
    val b = Thread(work)
    a.start(); b.start()
    a.join(); b.join()
    println(count)
}
public class Counter {
    static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable work = () -> { for (int i = 0; i < 100_000; i++) count++; };
        Thread a = new Thread(work), b = new Thread(work);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println(count);
    }
}
private val hits = AtomicInteger()
fun hit() { hits.incrementAndGet() }                // atomic, lock-free

private val views = LongAdder()
fun view() { views.increment() }                    // best under heavy contention; read with sum()

private var likes = 0
private val lock = Any()
fun like() = synchronized(lock) { likes++ }         // one critical section
fun likes() = synchronized(lock) { likes }          // reads must synchronize too, for visibility
private final AtomicInteger hits = new AtomicInteger();
void hit() { hits.incrementAndGet(); }              // atomic, lock-free

private final LongAdder views = new LongAdder();
void view() { views.increment(); }                  // best under heavy contention; read with sum()

private int likes;
synchronized void like() { likes++; }               // the whole method is one critical section
synchronized int likes() { return likes; }          // reads must synchronize too, for visibility

The flag nobody sees

Spot the bugA worker that never stops

Tap the line with the bug.

class Exporter : Runnable {
    private var running = true

    fun stop() { running = false }

    override fun run() {
        while (running) {
            exportNextBatch()
        }
    }
}
public class Exporter implements Runnable {
    private boolean running = true;

    public void stop() { running = false; }

    @Override
    public void run() {
        while (running) {
            exportNextBatch();
        }
    }
}

Safe publication

An object is safely published when another thread can’t see it half-constructed. Unsafe: assigning a new object to a plain field that another thread reads, because the reference may become visible before the constructor’s writes. Safe: storing it in a volatile or final field, an AtomicReference, a concurrent collection, or handing it over through a BlockingQueue or Future, or initializing it in a static initializer (class initialization is synchronized). Immutable objects with all-final fields are safe even when published through a data race, which is one more reason to prefer records and immutable value objects.

Deep diveWhy double-checked locking needs volatileInterview favorite

Lazy singletons were often written like this: check instance == null, lock, check again, then instance = new Helper(). Without volatile, the assignment of the reference can become visible to another thread before the writes inside Helper’s constructor. A second thread passes the first check (not null) without locking and uses a Helper whose fields are still zero.

Since Java 5, declaring the field volatile fixes it: the volatile write happens-after the constructor, and the reader’s volatile read happens-after that write. Simpler alternatives need no reasoning at all: the holder-class idiom (static class Holder { static final Helper INSTANCE = new Helper(); }, initialized lazily and thread-safely by the class loader), an enum singleton, or, in Spring, a singleton bean.

  • Only happens-before edges guarantee visibility: monitor unlock → lock, volatile write → read, start(), join(), and java.util.concurrent hand-offs. It’s transitive.
  • volatile = visibility and ordering, not atomic x++. Atomics = CAS read-modify-write; LongAdder under contention. Locks = atomicity of blocks, reads must lock too.
  • Safe publication: final fields, volatile, concurrent collections, queues; immutable objects are safe. Double-checked locking needs volatile (or use the holder idiom).

Check this part

  1. Why can count++ on a shared field lose updates?

  2. A boolean stop flag is written by one thread and read in a loop by another. What does it need?

  3. Does making the counter field volatile fix count++?

  4. Why does double-checked locking need the instance field to be volatile?

Threads can lose each other's updates (count++ is three steps) and may not see each other's writes at all without a happens-before edge. volatile gives visibility for single reads and writes, atomics and locks give atomic read-modify-write. Safe publication and final fields make objects visible correctly.

Part Not started

Locks, atomic maps and deadlocks

Using a thread-safe class doesn’t make your code thread-safe. A ConcurrentHashMap won’t corrupt itself when many threads use it, but two calls in a row are still two separate steps:

if (!sessions.containsKey(userId)) {         // thread A and B both see "missing"
    sessions.put(userId, new Session(userId)); // both create a session; one overwrites the other
}

This is called check-then-act, and the fix is to let the map do both steps as one: sessions.computeIfAbsent(userId, Session::new). The same goes for counters in a map: counts.merge(word, 1, Integer::sum), not get then put.

When several objects must change together (move money between two accounts), you need a lock around the whole change. Locks bring their own danger: if thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1, both wait forever. That’s a deadlock.

Thread-safe components don’t compose: invariants spanning several calls or several objects need atomic operations on one structure (compute, merge, putIfAbsent, replace(k, old, new)) or a lock around the compound action. ConcurrentHashMap locks per bin, so its compute* functions run under that bin’s lock: keep them short, never call slow I/O inside, and never modify the same map from within (that can throw “Recursive update” or hang). synchronized is reentrant, simple and, since JDK 24, no longer pins virtual threads; ReentrantLock adds tryLock with timeouts, interruptible locking, fairness and multiple conditions; ReadWriteLock and StampedLock (optimistic reads) help read-mostly data; immutable snapshots swapped through an AtomicReference (or CopyOnWriteArrayList for rarely changed lists of listeners) often beat locks entirely. Deadlocks need circular waiting, so a global lock order (by account id, for example) prevents them; tryLock with a timeout turns them into retries; thread dumps (jstack, jcmd Thread.print) report “Found one Java-level deadlock”.

Predict the output

Four threads each call counts.merge('apple', 1, Integer::sum) 1,000 times on one ConcurrentHashMap. What is counts.get('apple') afterwards?

val counts = ConcurrentHashMap<String, Int>()
val work = Runnable { repeat(1_000) { counts.merge("apple", 1, Int::plus) } }
val threads = List(4) { Thread(work) }
threads.forEach(Thread::start)
threads.forEach(Thread::join)
println(counts["apple"])
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
Runnable work = () -> { for (int i = 0; i < 1_000; i++) counts.merge("apple", 1, Integer::sum); };
List<Thread> threads = Stream.generate(() -> new Thread(work)).limit(4).toList();
threads.forEach(Thread::start);
for (Thread t : threads) t.join();
System.out.println(counts.get("apple"));

Two transfers, two locks

Spot the bugTransfers that freeze the server

Tap the line with the bug.

fun transfer(from: Account, to: Account, cents: Long) {
    synchronized(from) {
        synchronized(to) {
            from.withdraw(cents)
            to.deposit(cents)
        }
    }
}
void transfer(Account from, Account to, long cents) {
    synchronized (from) {
        synchronized (to) {
            from.withdraw(cents);
            to.deposit(cents);
        }
    }
}

Choosing the tool

NeedTool
One value, many writersAtomicLong (LongAdder if contended and read rarely)
Per-key updatesConcurrentHashMap.compute / merge / computeIfAbsent
Several fields change togethersynchronized or ReentrantLock around both reads and writes
Must not wait foreverlock.tryLock(200, MILLISECONDS) with a fallback
Read-mostly config or listenersimmutable snapshot in an AtomicReference, or CopyOnWriteArrayList
Many readers, rare writers, hot pathReentrantReadWriteLock or StampedLock optimistic reads (measure first)
Deep diveLongAdder vs AtomicLongInterview favorite

AtomicLong.incrementAndGet() is a compare-and-set loop on one memory location. Under heavy contention, many cores keep invalidating each other’s cache line and retrying, so throughput collapses as threads are added.

LongAdder spreads increments over several cells (roughly one per contending thread, padded to avoid sharing cache lines) and adds them up only when you call sum(). Increments scale almost linearly; the price is that sum() isn’t an atomic snapshot while writes continue, and the adder uses more memory. Use it for metrics and statistics; use AtomicLong when you need the exact current value, like a sequence number.

  • Thread-safe classes don’t compose: no get-then-put, use compute, merge, computeIfAbsent (short, no I/O, no recursive updates).
  • Deadlocks need circular waits: global lock order, or tryLock with a timeout; jstack finds them.
  • Prefer immutable snapshots and atomics; ReentrantLock for timeouts and interruptibility; read-write and stamped locks only when measured. synchronized no longer pins virtual threads since JDK 24.

Check this part

  1. How do you add a session to a ConcurrentHashMap only if the user has none, safely?

  2. What causes the deadlock in transfer(a, b) running at the same time as transfer(b, a)?

  3. What must never happen inside ConcurrentHashMap.compute()?

  4. When does LongAdder beat AtomicLong?

Keep check-then-act sequences atomic: one compute or merge call on a ConcurrentHashMap, not get followed by put. Locks taken in different orders deadlock; take them in one global order or use tryLock with a timeout. Choose synchronized, ReentrantLock, read-write locks or immutable data by need.

Part Not started

Executors and CompletableFuture

Creating a thread per task is expensive and has no limit. An ExecutorService keeps a pool of threads and a queue of tasks: you submit work, it runs on a free thread, and you get a Future to wait for the result.

CompletableFuture lets you describe what happens when a result arrives, without blocking a thread to wait for it: “load the price and the stock at the same time, then combine them, and if anything fails, show a fallback”.

Three rules prevent most problems:

  • Give I/O work its own executor. Without one, CompletableFuture.supplyAsync uses a shared pool sized for CPU work (one thread less than your cores). Blocking calls there starve everything else that uses it.
  • Always set a timeout (orTimeout, completeOnTimeout), or a slow dependency makes the future wait forever.
  • Shut executors down when the application stops (in Spring, let Spring manage them as beans).

ThreadPoolExecutor = core and max pool sizes, a work queue and a rejection policy. The Executors factory methods hide dangerous defaults: newFixedThreadPool uses an unbounded LinkedBlockingQueue (a backlog grows until the heap is gone), newCachedThreadPool creates unbounded threads. Production executors use bounded queues and an explicit rejection policy (CallerRunsPolicy for natural backpressure, or AbortPolicy with a 503), are sized from the work (CPU-bound ≈ cores; blocking ≈ cores × (1 + wait/compute), or virtual threads with a semaphore guarding the scarce resource), named for thread dumps, and shut down with shutdown() + awaitTermination (shutdownNow() interrupts). CompletableFuture: thenApply (transform), thenCompose (chain another future), thenCombine/allOf (join), exceptionally/handle (recover), orTimeout/completeOnTimeout (Java 9). The *Async variants without an executor run on ForkJoinPool.commonPool(); cancellation doesn’t interrupt the running task; exceptions arrive wrapped in CompletionException. On Java 21+, Executors.newVirtualThreadPerTaskExecutor() makes blocking style cheap again, and structured concurrency (StructuredTaskScope, still a preview API in Java 25) ties subtasks’ lifetimes and failures together.

@Service
class ProductPageService {
    private val io = Executors.newFixedThreadPool(32)                    // a pool for blocking calls

    fun load(sku: String): ProductPage {
        val price = CompletableFuture
            .supplyAsync({ pricing.priceFor(sku) }, io)
            .orTimeout(300, TimeUnit.MILLISECONDS)
        val stock = CompletableFuture
            .supplyAsync({ inventory.stockFor(sku) }, io)
            .completeOnTimeout(Stock.UNKNOWN, 200, TimeUnit.MILLISECONDS)  // fallback on timeout
            .exceptionally { Stock.UNKNOWN }                                // fallback on error

        return price.thenCombine(stock, ::ProductPage).join()              // both run at once
    }

    @PreDestroy
    fun close() = io.shutdown()
}
@Service
public class ProductPageService {
    private final ExecutorService io = Executors.newFixedThreadPool(32);   // a pool for blocking calls

    public ProductPage load(String sku) {
        CompletableFuture<Price> price = CompletableFuture
            .supplyAsync(() -> pricing.priceFor(sku), io)
            .orTimeout(300, TimeUnit.MILLISECONDS);
        CompletableFuture<Stock> stock = CompletableFuture
            .supplyAsync(() -> inventory.stockFor(sku), io)
            .completeOnTimeout(Stock.UNKNOWN, 200, TimeUnit.MILLISECONDS)   // fallback on timeout
            .exceptionally(e -> Stock.UNKNOWN);                             // fallback on error

        return price.thenCombine(stock, ProductPage::new).join();           // both run at once
    }

    @PreDestroy
    void close() { io.shutdown(); }
}

The page waits for the slower of the two calls, not their sum. If inventory is slow or fails, the page still shows the price with “stock unknown”; if pricing fails, join() throws, because the page can’t be shown without a price. In Kotlin code you’d usually write the same thing with coroutines (async/await); CompletableFuture is what Java libraries and older code use, and Kotlin calls it the same way.

A pool that eats the memory

Spot the bugAn email sender that crashes after a newsletter

Tap the line with the bug.

@Service
class Mailer {
    private val pool = Executors.newFixedThreadPool(4)

    fun sendLater(email: Email) {
        pool.submit { smtp.send(email) }        // about 1 second each
    }
}
@Service
public class Mailer {
    private final ExecutorService pool = Executors.newFixedThreadPool(4);

    public void sendLater(Email email) {
        pool.submit(() -> smtp.send(email));    // about 1 second each
    }
}

Exerciseeasy

Three calls, one deadline

A dashboard endpoint needs the user’s profile (required), their last orders (required) and recommendations (optional). Each comes from a blocking client call. Load all three in parallel, fail the endpoint if a required call fails or takes longer than 500 ms, and show an empty list if recommendations fail or take longer than 200 ms.

›

Start all three with supplyAsync on an I/O executor. Give recommendations its own timeout and fallback; then combine with allOf or thenCombine.

SolutionTry it yourself first
fun load(userId: Long): Dashboard {
    val profile = CompletableFuture.supplyAsync({ users.profile(userId) }, io)
    val orders = CompletableFuture.supplyAsync({ orderClient.lastOrders(userId) }, io)
    val recs = CompletableFuture.supplyAsync({ recClient.forUser(userId) }, io)
        .completeOnTimeout(emptyList(), 200, TimeUnit.MILLISECONDS)
        .exceptionally { emptyList() }

    return CompletableFuture.allOf(profile, orders, recs)
        .orTimeout(500, TimeUnit.MILLISECONDS)
        .thenApply { Dashboard(profile.join(), orders.join(), recs.join()) }
        .join()    // throws CompletionException if profile or orders failed or timed out
}
public Dashboard load(long userId) {
    var profile = CompletableFuture.supplyAsync(() -> users.profile(userId), io);
    var orders = CompletableFuture.supplyAsync(() -> orderClient.lastOrders(userId), io);
    var recs = CompletableFuture.supplyAsync(() -> recClient.forUser(userId), io)
        .completeOnTimeout(List.of(), 200, TimeUnit.MILLISECONDS)
        .exceptionally(e -> List.of());

    return CompletableFuture.allOf(profile, orders, recs)
        .orTimeout(500, TimeUnit.MILLISECONDS)
        .thenApply(done -> new Dashboard(profile.join(), orders.join(), recs.join()))
        .join();   // throws CompletionException if profile or orders failed or timed out
}

allOf completes when all three are done (or fails as soon as one fails), and the overall orTimeout caps the whole endpoint at 500 ms. A timed-out call keeps running on its thread, because completing a future doesn’t interrupt the task, so the clients still need their own HTTP timeouts. Map the CompletionException to a 503 or 504 in the controller advice.

Production details

  • Name threads (Thread.ofPlatform().name("mailer-", 0).factory(), or Spring’s ThreadPoolTaskExecutor with a prefix) so thread dumps and logs say what’s stuck.
  • Context doesn’t travel: MDC, security context and tracing are thread-local; wrap executors (Micrometer context propagation, Spring’s TaskDecorator) so async work keeps the request’s trace id.
  • Exceptions vanish from executed tasks into the thread’s uncaught handler, and from submitted tasks into a Future nobody reads; log them in the task or check the futures.
  • Virtual threads remove thread-count limits but not resource limits: guard database connections and rate-limited APIs with a Semaphore, and don’t pool virtual threads.
Deep diveWhy blocking calls in the common pool hurt everyoneInterview favorite

ForkJoinPool.commonPool() has one thread fewer than the number of CPU cores (so a 4-core container gets 3 threads) and is shared by the whole JVM: parallel streams, CompletableFuture’s *Async methods without an executor, and many libraries use it. It’s designed for short CPU work.

Put a 2-second HTTP call on it and three concurrent requests occupy all three threads; every parallel stream and async step in the process now waits behind them. The managed-blocking mechanism can add compensation threads only for code that cooperates with it, which ordinary blocking clients don’t. Always pass an explicit executor for anything that blocks.

  • Executors.newFixedThreadPool = unbounded queue, newCachedThreadPool = unbounded threads: build ThreadPoolExecutors with bounded queues and a rejection policy, sized for the work, named, shut down.
  • CompletableFuture: own executor for blocking work (not the common pool), orTimeout/completeOnTimeout, exceptionally/handle; cancelling doesn’t interrupt; failures arrive as CompletionException.
  • Thread-local context (MDC, security, tracing) needs explicit propagation. Virtual threads: no pooling, Semaphore for scarce resources.

Check this part

  1. Where does CompletableFuture.supplyAsync(task) run without an executor argument?

  2. Why always add a timeout to a CompletableFuture that waits on another service?

  3. What is dangerous about Executors.newFixedThreadPool(4) under a burst of tasks?

  4. A CompletableFuture times out with orTimeout. What happens to the task that was computing it?

Run work on an ExecutorService, never on raw threads: size pools for the work, bound their queues, and shut them down. CompletableFuture composes async steps; give blocking work its own executor instead of the common pool, add timeouts, and handle exceptions where the result is used.

Key takeaways

  • count++ on shared data loses updates; use AtomicInteger, LongAdder or a lock. A flag read in a loop by another thread must be volatile.
  • Thread-safe collections still need atomic operations: computeIfAbsent and merge, not get then put.
  • Take locks in one fixed order, or two threads can wait for each other forever.
  • Run tasks on executors with bounded queues; give blocking work its own executor and always set timeouts.
  • Visibility comes only from happens-before edges; volatile gives visibility, not atomicity; publish objects safely, prefer immutable ones.
  • Compose thread-safe parts with atomic map operations, lock ordering and immutable snapshots; know when LongAdder and tryLock help.
  • Build executors explicitly (bounded queue, rejection policy, names, shutdown) and keep blocking work off the common pool.
  • CompletableFuture timeouts don’t cancel work, exceptions arrive wrapped, and thread-local context must be propagated.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.