medium.com 13 min read Original Source

Multithreading in Java: From Novice to Staff Engineer

A program that spends most of its time waiting

Here is a small program. To build a page it needs three pieces of data: a user, their orders, and some recommendations. Each one comes from a different service and each call takes about a second. We fake the calls with Thread.sleep so you can run it anywhere.

public class Sequential {

    static String fetch(String what) {
        try {
            Thread.sleep(1000); // pretend this is a network call
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        return what + " (done)";
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String user = fetch("user");
        String orders = fetch("orders");
        String recs = fetch("recommendations");
        System.out.println(user + ", " + orders + ", " + recs);
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
    }
}
public class Sequential {

    static String fetch(String what) {
        try {
            Thread.sleep(1000); // pretend this is a network call
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        return what + " (done)";
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String user = fetch("user");
        String orders = fetch("orders");
        String recs = fetch("recommendations");
        System.out.println(user + ", " + orders + ", " + recs);
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
    }
}

Ignore the catch block for now. We will come back to it when we talk about interruption.

Run it and it takes a little over three seconds. The code is not wrong, but think about what the machine did during those three seconds. Almost nothing. The program was waiting, and it started waiting for the second call only after the first one returned, even though the calls have nothing to do with each other.

Multithreading is how you tell Java that some of this work can happen at the same time. This article is about what that costs you. The first gain is easy to get. The costs show up later, and they get bigger as the system does. We will go step by step, and each new tool appears only after you have seen the problem it exists for.

What a thread is

When you run java Sequential, the operating system starts a process. The JVM runs inside it, loads your classes, and creates a thread to run main. A thread is one sequence of instructions being executed, along with its own current position in the code. Every program you have written so far probably used one thread of its own, doing one thing at a time from top to bottom.

Two facts about threads matter more than anything else in this article.

Each thread has its own call stack. The stack holds the methods that are currently in progress, with their parameters and local variables. If two threads run the same method at the same time, each has its own copy of that method’s local variables.

All threads in a process share the heap. Every object created with new lives on the heap, and any thread that holds a reference to an object can read and modify it.

Combine the two and you get the rule that most concurrency bugs come from: local variables are private to a thread, and objects are shared as soon as more than one thread can reach them. When someone asks whether a piece of code is thread-safe, the useful version of the question is: which objects here can be reached by more than one thread, and what do those threads do to them?

You can ask Java which thread is running your code:

public class WhoAmI {
    public static void main(String[] args) {
        Thread t = Thread.currentThread();
        System.out.println(t.getName());     // main
        System.out.println(t.threadId());    // a number the JVM assigned
    }
}
public class WhoAmI {
    public static void main(String[] args) {
        Thread t = Thread.currentThread();
        System.out.println(t.getName());     // main
        System.out.println(t.threadId());    // a number the JVM assigned
    }
}

A running JVM has more threads than the ones you created. There are garbage collector threads, JIT compiler threads and a few others. Run jcmd <pid> Thread.print against any Java process to see them all.

Concurrency, parallelism, and the two reasons to add threads

A CPU core executes one instruction stream at a time. A machine with 8 cores can run 8 threads at the same instant, which is called parallelism. You can still have 500 threads. The operating system switches each core between them many times per second, giving each one a short slice of time. That switch is a context switch, and it has a cost. The word concurrency covers both situations: several tasks are in progress during overlapping periods of time, whether or not they are literally running at the same instant.

The distinction matters because there are two different reasons to use more than one thread, and they have different limits.

The first is waiting. In our program the threads would spend nearly all their time waiting for a network response. Waiting uses no CPU, so adding threads helps even on a single core. The limit is how many things you can usefully have in flight.

The second is computing. If the work is resizing images or hashing files, every thread needs a core while it runs. More threads than cores gives you nothing but context switches. The limit is the core count.

Keep this split in mind. It decides how you size thread pools later, and it is the whole reason virtual threads exist.

Your first threads

results[0] = fetch("user"));
Thread t2 = new Thread(() -> results[1] = fetch("orders"));
Thread t3 = new Thread(() -> results[2] = fetch("recommendations"));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println(String.join(", ", results));
System.out.println("took " + (System.currentTimeMillis() – start) + " ms");
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

public class Parallel {

    // same fetch() as before
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        String[] results = new String[3];
        Thread t1 = new Thread(() -> results[0] = fetch("user"));
        Thread t2 = new Thread(() -> results[1] = fetch("orders"));
        Thread t3 = new Thread(() -> results[2] = fetch("recommendations"));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println(String.join(", ", results));
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
    }
}
public class Parallel {

    // same fetch() as before
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        String[] results = new String[3];
        Thread t1 = new Thread(() -> results[0] = fetch("user"));
        Thread t2 = new Thread(() -> results[1] = fetch("orders"));
        Thread t3 = new Thread(() -> results[2] = fetch("recommendations"));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println(String.join(", ", results));
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
    }
}

This finishes in a little over one second. Three things are new here.

new Thread(runnable) creates a thread object but does not run anything. The lambda is a Runnable, a piece of code the thread will execute.

start() asks the JVM to create an operating system thread and begin running the Runnable on it. It returns immediately. If you call run() instead of start(), the code runs on your current thread, one task after another, and the program is slow again without any error. This is one of the most common beginner mistakes because nothing tells you it happened.

join() makes the calling thread wait until the target thread has finished. Without the joins, main would print the results before the other threads had written them.

There is a subtle point in this program. Three threads write into the same array and the main thread reads it. Why is that safe? Each thread writes to a different slot, so they don’t overwrite each other. The more important reason is that main reads the array only after join() returns, and join() comes with a guarantee that everything the finished thread did is visible to the caller. We will name that guarantee properly in a few sections. For now, notice that the program is correct because of a specific rule, not because it happened to work.

Threads that fail, and threads that never end

If code in a thread throws an exception that nobody catches, only that thread dies. The default handler prints the stack trace to standard error and the rest of the program carries on. In a service this means a background thread can die quietly while everything else looks healthy. You can install a handler with thread.setUncaughtExceptionHandler(...) to at least log it properly.

A JVM exits when its last non-daemon thread finishes. Threads you create are non-daemon by default. A thread marked with setDaemon(true) (before start()) does not keep the JVM alive. When a program refuses to exit after main returns, the cause is nearly always a non-daemon thread still running, often a thread pool that nobody shut down.

A thread is always in one of six states, available from thread.getState(): NEW (created, not started), RUNNABLE (running or ready to run), BLOCKED (waiting to enter a synchronized block), WAITING (waiting indefinitely, for example in join()), TIMED_WAITING (waiting with a timeout, for example in sleep), and TERMINATED. You will see these names in every thread dump you read in production, so it is worth recognizing them now.

One more limit of Runnable: it returns nothing and cannot throw checked exceptions. Our array trick is a workaround for that. Later we will see the proper tool.

The first bug

Here is a counter and two threads that increment it 100,000 times each.

{
for (int i = 0; i

public class Counter {
    private int count = 0;
    void increment() { count++; }
    int get() { return count; }
}

public class RaceDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Runnable task = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.increment();
            }
        };
        Thread a = new Thread(task);
        Thread b = new Thread(task);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(counter.get());
    }
}
public class Counter {
    private int count = 0;
    void increment() { count++; }
    int get() { return count; }
}

public class RaceDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Runnable task = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.increment();
            }
        };
        Thread a = new Thread(task);
        Thread b = new Thread(task);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println(counter.get());
    }
}

You would expect 200000. You will get a lower number, and a different one on each run. (With a very short loop it may print the right answer, which is part of the problem.)

The reason is that count++ looks like one operation but is three: read count from memory, add one, write the result back. Two threads can interleave those steps:

  • Thread A reads count and gets 5.
  • Thread B reads count and gets 5.
  • Thread A computes 6 and writes 6.
  • Thread B computes 6 and writes 6.

Two increments happened and the counter moved by one. One update was lost. This is a race condition: the result depends on the timing of the threads. Nothing in the JVM malfunctioned. The program did something the code allowed.

This kind of bug survives in real systems for a reason. It is not deterministic, so it passes the unit tests. It may need a certain level of load before the timing lines up, so it appears in production and not on your laptop. And it disappears when you add logging, because logging changes the timing. A bug that happens once in a million operations is invisible in a test, and it happens several times a day in a service that handles hundreds of requests per second.

The same problem has a second common shape, check-then-act:

if (!cache.containsKey(key)) {
    cache.put(key, loadFromDatabase(key));
}
if (!cache.containsKey(key)) {
    cache.put(key, loadFromDatabase(key));
}

Two threads can both see the key missing, and both load it. If cache is a plain HashMap it is worse: HashMap is not designed for concurrent modification, and concurrent writes can lose entries or leave the structure broken.

What we need is a way to say that a block of code runs in one thread at a time. That property is called mutual exclusion.

synchronized

class Counter {
    private int count = 0;
    synchronized void increment() { count++; }
    synchronized int get() { return count; }
}
class Counter {
    private int count = 0;
    synchronized void increment() { count++; }
    synchronized int get() { return count; }
}

Run RaceDemo again and you get 200000 every time.

Every Java object has a lock built into it, called its monitor. A thread entering a synchronized method must first acquire the monitor of the object. If another thread holds it, the entering thread moves to the BLOCKED state until the monitor is released. The monitor is released when the method exits, including when it exits through an exception, so you cannot forget to release it. The lock is reentrant: a thread that already holds a monitor can enter another synchronized block on the same object without blocking itself.

You can choose the object to lock with a block:

class Counter {
    private final Object lock = new Object();
    private int count = 0;
    void increment() {
        synchronized (lock) {
            count++;
        }
    }
}
class Counter {
    private final Object lock = new Object();
    private int count = 0;
    void increment() {
        synchronized (lock) {
            count++;
        }
    }
}

A synchronized instance method locks this. A static synchronized method locks the Class object. The block form lets you choose.

Some rules that save a lot of debugging time:

  1. The lock only works if everyone uses the same one. Two threads synchronizing on different objects exclude nothing. A common version of this bug is synchronizing on a local variable or on a new object created on every call.
  2. Prefer a private lock object over this. With synchronized (this), any caller holding a reference to your object can also synchronize on it and interfere with your locking. A private final Object removes that possibility. For the same reason, never lock on a String literal, a boxed Integer, or any object that unrelated code might also lock on.
  3. Protect reads as well as writes. The get() method above is synchronized on purpose. The next section shows why a read without the lock is a bug even though it only reads.
  4. Keep the locked section small. While one thread holds the lock, every other thread that needs it waits. Do the slow work, such as computation or I/O, outside the lock and touch the shared state only inside it.
  5. Do not call code you don’t control while holding a lock. A callback, a listener or an overridable method may block for a long time or try to take other locks. That is how deadlocks start, and we will get to them.

An uncontended synchronized block is cheap on a modern JVM. The cost appears when many threads want the same lock, and we will return to that when we talk about contention.

A different bug: threads that don’t see each other’s writes

Synchronization fixed the lost update. Now look at a program that has no lost update at all and still misbehaves.

{
long n = 0;
while (running) {
n++;
}
System.out.println("worker stopped after " + n + " loops");
});
worker.start();
Thread.sleep(1000);
running = false;
System.out.println("flag set to false");
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

public class StopFlag {
    private static boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            long n = 0;
            while (running) {
                n++;
            }
            System.out.println("worker stopped after " + n + " loops");
        });
        worker.start();
        Thread.sleep(1000);
        running = false;
        System.out.println("flag set to false");
    }
}
public class StopFlag {
    private static boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            long n = 0;
            while (running) {
                n++;
            }
            System.out.println("worker stopped after " + n + " loops");
        });
        worker.start();
        Thread.sleep(1000);
        running = false;
        System.out.println("flag set to false");
    }
}

On many machines this prints flag set to false and then never exits. The worker keeps spinning. Whether it hangs depends on the JVM version, the flags and the CPU, and on some runs it stops normally. Java makes no promise either way, and that is the lesson.

There are two reasons the worker may not see the change. The JIT compiler optimizes the loop on the assumption that, within one thread, nobody changes running while the loop is running, so it may read the variable once and reuse the value forever. And even without that optimization, a write made by one core may sit in the core’s store buffer or cache for a while before other cores see it.

So concurrency gives us three separate problems, not one:

  • Atomicity: an operation made of several steps can be interleaved with another thread’s steps. This was the counter.
  • Visibility: a write by one thread may not be seen by another thread, or not for a long time. This is the stop flag.
  • Ordering: the compiler and the CPU may reorder operations that look independent, so another thread can observe your writes in a different order than your code made them.

Ordering deserves an example, because it is the least intuitive of the three:

// shared fields
int data = 0;
boolean ready = false;
// thread A
data = 42;
ready = true;
// thread B
if (ready) {
    System.out.println(data);   // is it always 42?
}
// shared fields
int data = 0;
boolean ready = false;
// thread A
data = 42;
ready = true;
// thread B
if (ready) {
    System.out.println(data);   // is it always 42?
}

Without any ordering rule it can print 0. Thread B may observe ready = true before it observes data = 42.

For the stop flag, Java gives us a keyword:

private static volatile boolean running = true;
private static volatile boolean running = true;

With volatile, a read of the variable always sees the most recent write by any thread, and the JIT is not allowed to keep the value in a register across iterations. It also gives an ordering guarantee: everything a thread did before writing a volatile variable is visible to any thread that later reads that variable and sees the new value. In the example above, making ready volatile makes the program correct, because data = 42 happens before the volatile write.

What volatile does not give you is atomicity of compound operations. A volatile int count with count++ is still the lost-update bug from earlier, because the three steps can still interleave. Use volatile when one thread writes and others read, and the new value does not depend on the old one: stop flags, status fields, or a reference to an immutable object that you replace as a whole (a configuration snapshot, for example).

The Java Memory Model, as much as you need

We now have three tools (synchronized, volatile and join) that each seem to produce some guarantee about what a thread can see. The Java Memory Model (JMM) is the specification that puts them under one rule.

The rule is called happens-before. If action A happens-before action B, then A’s effects, including every write it made, are visible to B, and A is ordered before B. If there is no happens-before relationship between a write in one thread and a read in another, Java guarantees nothing about what the reader sees. That situation is called a data race, and a program with a data race has behavior that depends on the JVM and the hardware.

The happens-before rules you will actually use:

  • Program order. Within one thread, each action happens-before the next one in the code.
  • Monitor lock. Releasing a monitor happens-before any later acquisition of the same monitor. This is why synchronized fixes visibility as well as atomicity, and why the getter in Counter must be synchronized on the same lock as the setter. A reader that doesn’t take the lock has no edge connecting it to the writer.
  • Volatile. A write to a volatile variable happens-before every later read of that same variable.
  • Thread start. Calling start() happens-before everything the new thread does.
  • Thread termination. Everything a thread did happens-before another thread returns from join() on it. This is the rule that made our array of results safe.
  • Transitivity. If A happens-before B and B happens-before C, then A happens-before C.

The classes in java.util.concurrent extend this list. Submitting a task to an executor happens-before the task runs. The task’s actions happen-before Future.get() returns. Putting an object into a concurrent collection happens-before another thread retrieves it. The package documentation lists these under “memory consistency properties”.

If you remember one sentence from this section, make it this one: to share data between threads correctly, you must be able to point at a happens-before edge that connects the write to the read. If you can’t, the code is wrong even when every test passes.

What the hardware is doing

You don’t need hardware knowledge to write correct code, but it explains why the rules exist. Each core has its own caches and a store buffer, so a write does not reach other cores the instant it executes. CPUs and compilers also reorder instructions to keep the pipeline full, as long as the result looks the same to a single thread. The JMM is the contract that tells the JVM where it must stop doing that: at volatile accesses, at monitor entry and exit, and at the other points in the list above. The JVM inserts the necessary memory barriers at those points.

One practical consequence matters in 2026. x86 processors have a fairly strong memory ordering, so a number of data races never show up on them. ARM processors, which now run a large share of cloud workloads (AWS Graviton, for example) and every recent Mac, are allowed more reordering. Code with a data race that has run quietly on x86 servers for years can start failing after a move to ARM. The code was wrong before. The hardware just never exposed it.

Atomics: a cheaper way to protect one variable

synchronized works, but a thread that fails to get the lock is blocked and parked by the operating system, and waking it later takes time. For a single counter that is a lot of machinery. CPUs offer a cheaper primitive for this case: compare-and-swap (CAS). It says: set this memory location to a new value only if it still holds the value I expect, and tell me whether it worked.

Java exposes it in the java.util.concurrent.atomic package:

private final AtomicInteger count = new AtomicInteger();

void increment() {
    count.incrementAndGet();
}
private final AtomicInteger count = new AtomicInteger();

void increment() {
    count.incrementAndGet();
}

No lock, no blocked threads. The general pattern behind it is a retry loop:

int current;
do {
    current = count.get();
} while (!count.compareAndSet(current, current + 1));
int current;
do {
    current = count.get();
} while (!count.compareAndSet(current, current + 1));

Read the value, compute the new one, try to swap it in, and if another thread changed the value in the meantime, start over. (On x86 the JIT turns incrementAndGet into a single atomic add instruction, so the loop above is the general form that compareAndSet makes possible, not what literally runs for this method.) Atomic classes also carry the visibility guarantees of volatile, so you get atomicity and visibility together for that one variable.

Three limits to know:

It protects one variable. If two fields must change together (a balance and a transaction count, say), two atomics do not make the pair atomic. Keep both values in one immutable object and swap it with an AtomicReference, or use a lock.

The update function may run more than once. AtomicReference.updateAndGet(fn) retries when it loses a race, so fn must have no side effects.

Lock-free is not contention-free. Under heavy contention, many threads fail the CAS and retry, and the cache line holding the variable bounces between cores. For counters that are written far more often than they are read, such as request metrics, LongAdder is built for the job. It spreads updates over several internal cells and adds them up when you call sum(). The trade is that sum() is not an atomic snapshot while updates are running, and you cannot do “increment only if below a limit” with it. Use AtomicLong when the exact current value drives a decision, and LongAdder when you only report it.

One more note on CAS: it compares values, not history. If a value changes from A to B and back to A, a CAS expecting A succeeds even though something happened in between. This is the ABA problem. It rarely matters for counters, but it matters in lock-free data structures, and AtomicStampedReference exists for those cases.