Albaraa Ahmed/ Writing
Portfolio
JavaConcurrencyMultithreadingJava21

Java Concurrency, Hands-On #1: Multithreading Basics

Dec 3, 20265 min read
Part 1 of 2 · Java Concurrency
  1. Java Concurrency, Hands-On #1: Multithreading Basics
  2. Java Concurrency, Hands-On #2: Synchronization

Concurrency is one of those topics you can read about for weeks and still not feel. The bugs depend on timing, the output changes every run, and most explanations stay abstract.

So I built a small lab where every concept is a runnable lesson, and every line of output tells you which thread did what, and when. This series walks through it, one lesson per article:

#Lesson
1Multithreading basics (this article)
2Synchronization
3ExecutorService
4CompletableFuture
5Concurrent collections
6Virtual threads
7Capstone: a coffee shop that uses all of it

Everything is set in a coffee shop: baristas are threads, the espresso machine is a lock, the order rail is a queue. It sounds silly, but it makes the ideas stick.

Code: github.com/baarayy/advanced-java-section · Java 21, no frameworks.

Running the lab

The Maven wrapper is included, so you only need JDK 21 or newer:

bash
git clone https://github.com/baarayy/advanced-java-section
cd advanced-java-section
./mvnw -q compile exec:java -Dexec.args=1     # Windows: mvnw.cmd ...

Every line of output looks like this:

[  931 ms] [barista-2           ] Brewing espresso...
   ^ time since start   ^ the thread that printed it

Read the thread column first. It tells you whether things really ran in parallel. A small Log helper adds it to every line:

Log.javajava
public static void log(String format, Object... args) {
    long ms = (System.nanoTime() - START) / 1_000_000;
    System.out.println(String.format("[%5d ms] [%-20s] %s", ms, threadName(), String.format(format, args)));
}

And Work.io(ms) simulates slow I/O (a network call, a database query, brewing a coffee) by sleeping.

What is a thread?

A thread is an independent path of execution inside your program. Every Java program starts with one, called main. When you start more, they run at the same time: truly in parallel on different CPU cores, or taking turns on the same core.

Two facts explain almost everything that follows:

  • Each thread has its own call stack. Local variables belong to one thread.
  • All threads share the same heap. Objects and fields are visible to every thread.

That sharing is what makes threads useful, and it's also the source of every bug in the next article. For now, let's just make some threads.

1. Three ways to create a thread

Lesson1Threads.javajava
// a) A Runnable (here a lambda) handed to a Thread. The classic way.
Thread a = new Thread(() -> log("Hi from a Runnable"), "barista-runnable");

// b) Java 21's builder: name, daemon flag, etc. in one fluent call.
Thread b = Thread.ofPlatform().name("barista-builder").unstarted(() -> log("Hi from the builder"));

// c) Subclassing Thread works, but it couples "what to do" with "how it runs". Avoid it.
Thread c = new Thread("barista-subclass") {
    @Override
    public void run() {
        log("Hi from a Thread subclass");
    }
};

a.start();
b.start();
c.start();
[   12 ms] [barista-runnable    ] Hi from a Runnable
[   13 ms] [barista-builder     ] Hi from the builder
[   14 ms] [barista-subclass    ] Hi from a Thread subclass

Run it a few times and the order of those three lines can change. Nothing guarantees which thread runs first. That's the first rule of concurrency: unless you coordinate threads, you don't control their order.

Prefer option (a) or (b). Passing a Runnable keeps what to do separate from how it runs, which is exactly what lets you hand the same task to a thread pool later (lesson 3) or a virtual thread (lesson 6). The Java 21 builder also has .factory(), which creates threads named barista-1, barista-2, and so on. We'll use that a lot.

2. start() vs run()

The most common beginner bug:

Lesson1Threads.javajava
Thread t = new Thread(() -> log("I am running on thread: %s", Thread.currentThread().getName()), "barista-1");

t.run();   // WRONG: just a normal method call. Runs on "main", no new thread is created.
t.start(); // RIGHT: the JVM creates a new thread and calls run() on it.
[   16 ms] [main                ] I am running on thread: main
[   17 ms] [barista-1           ] I am running on thread: barista-1

run() is just the method that holds the task. Calling it yourself runs the task on the current thread, synchronously. Only start() asks the JVM for a new thread. The code compiles either way, which is why this bug survives code review.

3. join(): waiting for a thread, and the speed-up

Three orders, each taking 300 ms to brew. First one barista, then three:

Lesson1Threads.javajava
long sequential = Work.timeMillis(() -> {
    for (String drink : orders) {
        brew(drink);
    }
});

long parallel = Work.timeMillis(() -> {
    List<Thread> baristas = new ArrayList<>();
    for (int i = 0; i < orders.length; i++) {
        String drink = orders[i];
        baristas.add(Thread.ofPlatform().name("barista-" + (i + 1)).start(() -> brew(drink)));
    }
    joinAll(baristas); // without join(), main would measure ~0 ms and move on
});
[   18 ms] [main                ] Brewing latte...
[  318 ms] [main                ] latte ready
[  319 ms] [main                ] Brewing espresso...
[  619 ms] [main                ] espresso ready
[  620 ms] [main                ] Brewing cappuccino...
[  920 ms] [main                ] cappuccino ready
[  921 ms] [main                ] One barista, three coffees in a row: 903 ms
[  931 ms] [barista-1           ] Brewing latte...
[  931 ms] [barista-2           ] Brewing espresso...
[  932 ms] [barista-3           ] Brewing cappuccino...
[ 1231 ms] [barista-1           ] latte ready
[ 1232 ms] [barista-2           ] espresso ready
[ 1232 ms] [barista-3           ] cappuccino ready
[ 1232 ms] [main                ] Three baristas at once:              310 ms

903 ms down to 310 ms. Look at the thread column: in the first half everything happens on main, one after another. In the second half, three different threads start within the same millisecond.

join() is what makes the measurement honest. main starts the three baristas, then waits for each to finish. Remove the joinAll call and main reports about 0 ms, because starting a thread returns immediately. The work happens later, without main knowing.

Starting a thread returns immediately. If you need the result, or need to know it's done, you have to wait for it.

4. Thread states

A thread moves through a small set of states, and getState() shows them. That's useful when debugging a stuck app:

Lesson1Threads.javajava
Thread t = new Thread(() -> Work.io(200), "sleepy-barista");
log("Before start():   %s", t.getState());
t.start();
Work.io(50);
log("While sleeping:   %s", t.getState());
join(t);
log("After it ended:   %s", t.getState());
[ 1233 ms] [main                ] Before start():   NEW
[ 1284 ms] [main                ] While sleeping:   TIMED_WAITING
[ 1434 ms] [main                ] After it ended:   TERMINATED
StateMeaning
NEWCreated, start() not called yet
RUNNABLERunning, or ready to run and waiting for a CPU
BLOCKEDWaiting to enter a synchronized block another thread holds (lesson 2)
WAITINGWaiting with no time limit, e.g. join() or wait()
TIMED_WAITINGWaiting with a time limit, e.g. sleep(200)
TERMINATEDFinished

When a production app hangs, a thread dump (jstack <pid>) lists every thread with exactly these states. A wall of BLOCKED threads usually means lock contention or a deadlock.

5. Stopping a thread: ask, don't force

You can't safely force a thread to stop. (Thread.stop() exists, but it's deprecated because killing a thread mid-update can leave objects half-written.) Instead, you ask it to stop with interrupt(), and the thread checks for that request and stops cleanly:

Lesson1Threads.javajava
Thread barista = Thread.ofPlatform().name("night-barista").start(() -> {
    int cups = 0;
    while (!Thread.currentThread().isInterrupted()) { // check the flag in your loop
        try {
            Thread.sleep(100); // blocking calls throw InterruptedException when interrupted
            cups++;
        } catch (InterruptedException e) {
            log("Interrupted while brewing, cleaning up after %d cups", cups);
            Thread.currentThread().interrupt(); // catching the exception CLEARS the flag: set it again
        }
    }
    log("Shift over, goodbye");
});

Work.io(350);
log("Closing time: asking night-barista to stop");
barista.interrupt();
[ 1787 ms] [main                ] Closing time: asking night-barista to stop
[ 1788 ms] [night-barista       ] Interrupted while brewing, cleaning up after 3 cups
[ 1788 ms] [night-barista       ] Shift over, goodbye

An interrupt reaches a thread in one of two ways:

  1. If the thread is running normally, its interrupt flag is set, and isInterrupted() returns true.
  2. If it's blocked in sleep(), wait(), join() or similar, that call throws InterruptedException.

Here's the trap: throwing InterruptedException clears the flag. If the catch block doesn't call Thread.currentThread().interrupt() again, the while loop sees a clean flag and keeps brewing forever. The stop request was swallowed.

This is one of the most common bugs in real Java code:

java
try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    // ignore   <- the "please stop" request is lost here
}

The rule: when you catch InterruptedException, either rethrow it or restore the flag. The lab's Work.io() helper does exactly that before giving up.

6. Exceptions inside threads

What happens when a thread throws?

Lesson1Threads.javajava
Thread clumsy = new Thread(() -> {
    throw new IllegalStateException("dropped the cup");
}, "clumsy-barista");

clumsy.setUncaughtExceptionHandler((thread, ex) ->
        log("Handler caught '%s' from %s", ex.getMessage(), thread.getName()));
clumsy.start();
[ 1791 ms] [clumsy-barista      ] Handler caught 'dropped the cup' from clumsy-barista
[ 1791 ms] [main                ] main is still alive: an exception kills only the thread that threw it

An exception kills only the thread that threw it. main keeps going and never finds out. Without a handler, the stack trace is printed to System.err and that's it: no crash, no error returned to anyone.

That's convenient and dangerous at the same time. In lesson 3 we'll see how ExecutorService and Future carry exceptions back to the code that asked for the work.

Common mistakes

  • Calling run() instead of start(). It compiles, and nothing runs in parallel.
  • Swallowing InterruptedException. Rethrow it or call Thread.currentThread().interrupt().
  • Using Thread.stop(). Use interrupt() and let the thread stop itself.
  • Forgetting join() when you need the work to be finished before moving on.
  • One new platform thread per task in a server. Platform threads are expensive (about 1 MB of stack each). Use a pool (lesson 3) or virtual threads (lesson 6).

Try it yourself

  1. In joinAndSpeedup, delete the joinAll(baristas) line. What time is printed, and why?
  2. Add a 4th and a 5th drink. Does the parallel time change? Why not?
  3. In interruption, delete the Thread.currentThread().interrupt() line in the catch. What happens? (Press Ctrl+C to stop it.)

Next: Synchronization

Threads share the heap, and so far that has been harmless because nobody wrote to the same data at the same time. In the next article, four baristas drop tips into one shared jar using tips++. They should collect 4,000,000 tips. In my run, they collected 2,454,514.

We'll see where the other million and a half went, and three different ways to fix it.


Source code: github.com/baarayy/advanced-java-section · This lesson: Lesson1Threads.java

Keep reading