Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Threads in Java

    A Thread object represents one thread of execution. Its work is a Runnable — a functional interface with one method, run() — usually

    Chapter 1 of 125 min read

    Start With the Problem#

    StudyBuddy's backend receives 1,000 requests at the same moment during exam week. Many of them ask the AI to generate a quiz, which means waiting ~3 seconds for an external AI API. Handling them one after another would mean the thousandth student waits 50 minutes.

    So the server must work on many requests at once — using several threads, and all 8 CPU cores. But the moment several threads touch the same data, things break in ways that single-threaded code never does:

    • the "total quizzes generated" counter comes out wrong (Operating Systems Ch 8);

    • a thread sets a "shutting down" flag, and another thread never sees it and keeps running forever;

    • two students spend the last AI credit at the same time;

    • two threads each hold one lock and wait for the other's — the server freezes;

    • a HashMap shared by threads silently loses data, or crashes.

    Java gives you tools for every one of these. This file shows each problem happening for real, then the tool that fixes it.

    The Plain Picture#

    A kitchen with one cook can make one dish at a time. Hire more cooks and several dishes progress at once — sharing the same kitchen, fridge and counters (Operating Systems Ch 7).

    The Real Names#

    • A Thread object represents one thread of execution. Its work is a Runnable — a functional interface with one method, run() — usually written as a lambda (Modern Java Ch 1).

    • start() asks the operating system to run it concurrently. join() waits until it finishes.

    • Every Java program starts with one thread, main.

    Under the Hood#

    Java
    Thread t = new Thread(
        () -> System.out.println("hello from " + Thread.currentThread().getName()),
        "worker-1"
    );
    
    System.out.println("state before start: " + t.getState()); // state before start: NEW
    
    t.start();
    
    t.join(); // hello from worker-1
    
    System.out.println("state after join: " + t.getState()); // state after join: TERMINATED

    start() vs run() — a classic trick question:

    Java
    Thread r = new Thread(() ->
        System.out.println("run() on " + Thread.currentThread().getName())
    );
    
    r.run(); // run() on main      ← NO new thread! It's just a normal method call

    Calling run() directly runs the code on the current thread. Only start() creates a new one.

    Thread states (Thread.getState()) — Java's names for the process states in Operating Systems Ch 3:

      NEW ──start()──▶ RUNNABLE ◀──────────────────────────────────┐
                         │  (running, or ready and waiting for a core)│
                         ├── waiting to enter a synchronized block ──▶ BLOCKED ─────┤
                         ├── wait() / join() / park() with no timeout ─▶ WAITING ──┤
                         ├── sleep(ms) / wait(ms) / join(ms) ──────────▶ TIMED_WAITING
                         └── run() finishes ──▶ TERMINATED

    Other basics:

    • Thread.sleep(ms) pauses the current thread (TIMED_WAITING); it throws the checked InterruptedException.

    • Interruption is Java's polite "please stop": t.interrupt() sets a flag and wakes the thread from sleep/wait with an InterruptedException. Handle it by finishing up, and restore the flag with Thread.currentThread().interrupt() if you can't stop right there. Never silently swallow it.

    • Daemon threads (t.setDaemon(true)) don't keep the JVM alive; the program can exit while they run. Normal (non-daemon) threads keep it alive until they finish.

    Why you rarely write new Thread(...) in real code: creating an OS thread costs memory (a stack of ~1 MB by default — Operating Systems Ch 6) and time. Real code reuses threads through pools (next chapter).

    Check yourself

    4 questions
    1

    start() vs run()?

    Show answer

    start() creates a new thread that runs run(); calling run() directly just executes it on the current thread.

    2

    What's the difference between BLOCKED and WAITING?

    Show answer

    BLOCKED = waiting to acquire a monitor lock for synchronized; WAITING = waiting indefinitely for another thread (e.g. wait, join).

    3

    What should code do when it catches InterruptedException?

    Show answer

    Stop what it's doing cleanly, or restore the interrupt flag with Thread.currentThread().interrupt() — never ignore it.

    4

    What is a daemon thread?

    Show answer

    A background thread that doesn't prevent the JVM from exiting.