Java thread basics

A thread is an independent path of execution with its own call stack, sharing the heap with every other thread in the JVM. This page explains what a Java thread is underneath, creates threads in each of the ways the JDK offers, follows a thread through its six states, and shows join, interruption, failure handling and daemon threads running. It ends by measuring what platform and virtual threads cost.

Contents

What a Java thread is

A running Java program is a set of threads. Each thread has its own call stack, holding the local variables and the chain of method calls it is in the middle of, and its own program counter. All threads share the heap, where objects live. That sharing is what makes threads useful, because they can work on the same data, and what makes them hard, because two threads can change the same object at the same moment.

Since Java 21 there are two kinds of thread behind the same java.lang.Thread class:

  • A platform thread is a thin wrapper around an operating system thread. The OS scheduler decides when it runs, and it reserves a fixed stack, 1 MB by default on 64-bit Linux (the -Xss option, or ThreadStackSize = 1024 KB). Creating one is a system call, so thousands are fine and hundreds of thousands are not.
  • A virtual thread (JEP 444, final in Java 21) is scheduled by the JVM onto a small pool of platform threads called carriers. When it blocks on sleep, a lock or most I/O, the JVM unmounts it and the carrier runs another virtual thread. Its stack lives on the heap and grows as needed, so a program can have millions of them.

The JVM starts with a main thread plus several system threads of its own (garbage collector, JIT compiler, finalizer and others). The program keeps running until every non-daemon thread has finished, or until System.exit is called.

Ways to create and start a thread
ApproachSinceBest for
Subclass Thread and override runJava 1.0Rarely the right choice; it mixes the task with how it is run
new Thread(Runnable, name)Java 1.0A few long-lived platform threads in older code
Thread.ofPlatform() builderJava 21Platform threads with names, daemon flag or stack size set in one place
Thread.ofVirtual(), Thread.startVirtualThreadJava 21Many tasks that spend most of their time waiting
ExecutorServiceJava 5Most real workloads: thread reuse, results, shutdown

The examples are complete programs, compiled and run on JDK 21. The ones that use timing print stable values on purpose; where something could vary between runs, the text says so.

Creating and starting threads

The program creates a thread in each of the four direct ways and prints the name of the thread that runs each piece of code, then shows the two mistakes beginners make most often.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadFactory;

public class CreateThreads {

    // 1. Subclassing Thread: works, but ties the task to one way of running it
    static class Greeter extends Thread {
        Greeter() {
            super("greeter");
        }

        @Override
        public void run() {
            System.out.println("subclass runs in    " + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main runs in        " + Thread.currentThread().getName());

        Thread subclass = new Greeter();
        subclass.start();
        subclass.join();

        // 2. A Runnable (here a lambda) handed to a Thread: the classic way
        Thread worker = new Thread(() ->
                System.out.println("Runnable runs in    " + Thread.currentThread().getName()),
                "worker-1");
        worker.start();
        worker.join();

        // 3. Thread.Builder (Java 21): named, numbered threads from one factory
        ThreadFactory factory = Thread.ofPlatform().name("pool-", 1).factory();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            threads.add(factory.newThread(() -> { }));
        }
        for (Thread t : threads) {
            System.out.println("builder made        " + t.getName() + ", state " + t.getState());
        }

        // 4. A virtual thread (Java 21): same Thread API, scheduled by the JVM
        Thread virtual = Thread.ofVirtual().name("virtual-1").start(() -> {
            Thread me = Thread.currentThread();
            System.out.println("virtual runs in     " + me.getName()
                    + ", isVirtual=" + me.isVirtual() + ", daemon=" + me.isDaemon());
        });
        virtual.join();

        // Trap 1: run() is an ordinary method call, so no new thread is created
        Thread notStarted = new Thread(() ->
                System.out.println("run() executes in   " + Thread.currentThread().getName()));
        notStarted.run();

        // Trap 2: a thread can be started only once
        try {
            worker.start();
        } catch (IllegalThreadStateException e) {
            System.out.println("start() twice       IllegalThreadStateException");
        }
    }
}

Output:

Output
main runs in        main
subclass runs in    greeter
Runnable runs in    worker-1
builder made        pool-1, state NEW
builder made        pool-2, state NEW
builder made        pool-3, state NEW
virtual runs in     virtual-1, isVirtual=true, daemon=true
run() executes in   main
start() twice       IllegalThreadStateException
  • The task of a thread is a Runnable: a method with no arguments and no result, usually written as a lambda. Passing a Runnable keeps the task independent, so the same lambda can later go to an executor or a virtual thread unchanged. That is why subclassing Thread is discouraged.
  • Thread.ofPlatform().name("pool-", 1) numbers the threads it creates: pool-1, pool-2, pool-3. A builder's factory() gives a ThreadFactory, which is what executors accept. Threads from newThread are created in state NEW and are not running yet.
  • The virtual thread reports isVirtual=true and daemon=true. Virtual threads are always daemon threads, and calling setDaemon(false) on one throws IllegalArgumentException.
  • "run() executes in main" is the first trap. run() is an ordinary method, so calling it runs the task on the current thread. The code compiles and produces the right result, just without any concurrency, which is why the mistake is easy to miss.
  • The second trap: a Thread object can be started once. Calling start() again throws IllegalThreadStateException, even after the thread has finished. To repeat the work, create a new thread or use an executor.

Give threads names. A name costs nothing and is what appears in logs, stack traces and thread dumps; "Thread-7" tells you nothing at 3 a.m. Each thread also has a numeric threadId() (Java 19; it replaced the deprecated getId()).

The six thread states

getState() returns one of the six values of Thread.State. The program puts threads into each state on purpose: a sleeping thread, one in wait(), and one trying to enter a synchronized block while main holds the lock.

Java
public class Lifecycle {

    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();

        Thread sleeper = new Thread(() -> {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        System.out.println("before start:     " + sleeper.getState());
        sleeper.start();
        Thread.sleep(100);
        System.out.println("during sleep:     " + sleeper.getState());
        sleeper.join();
        System.out.println("after join:       " + sleeper.getState());

        Thread blocked = new Thread(() -> {
            synchronized (lock) {
                System.out.println("blocked thread finally got the lock");
            }
        });
        Thread waiter = new Thread(() -> {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        waiter.start();
        Thread.sleep(100);
        System.out.println("in lock.wait():   " + waiter.getState());

        synchronized (lock) {                     // main holds the lock...
            blocked.start();
            Thread.sleep(100);
            System.out.println("waiting for lock: " + blocked.getState());
            lock.notifyAll();
        }                                          // ...and releases it here
        blocked.join();
        waiter.join();
        System.out.println("all done:         " + blocked.getState() + ", " + waiter.getState());
    }
}

Output:

Output
before start:     NEW
during sleep:     TIMED_WAITING
after join:       TERMINATED
in lock.wait():   WAITING
waiting for lock: BLOCKED
blocked thread finally got the lock
all done:         TERMINATED, TERMINATED
Thread states and what puts a thread into each one
StateMeaningTypical cause
NEWCreated, not startedBefore start()
RUNNABLERunning, or ready and waiting for a CPUExecuting code, including blocking socket and file I/O
BLOCKEDWaiting to enter a synchronized block or methodAnother thread holds that monitor
WAITINGWaiting with no time limitwait(), join(), LockSupport.park(), Lock.lock()
TIMED_WAITINGWaiting with a time limitsleep(ms), wait(ms), join(ms), parkNanos
TERMINATEDFinishedrun returned or threw
  • The waiting thread is WAITING, not BLOCKED: wait() releases the monitor and parks until notified. The third thread is BLOCKED because it has not entered the monitor at all. When main calls notifyAll and leaves its block, both can proceed.
  • Only synchronized produces BLOCKED. A thread waiting for a ReentrantLock shows as WAITING, because locks in java.util.concurrent are built on LockSupport.park. Keep that in mind when reading a thread dump.
  • A thread blocked in a socket read is RUNNABLE from the JVM's point of view, even though it uses no CPU.

The short sleeps in main give the other threads time to reach a state before it is printed. They keep the demo readable, but sleep is never a correct way to coordinate threads in real code: use join, latches or queues.

Waiting for a thread: join

join() blocks until a thread has terminated. The program splits the sum 1 + 2 + ... + 1,000,000 over two threads, because the exact answer, n(n + 1) / 2, is easy to check. It then shows that join with a timeout only stops the waiting.

Java
public class JoinAndTimeout {

    public static void main(String[] args) throws InterruptedException {
        // Split a sum over two threads; each writes its own slot of the array
        long[] partial = new long[2];
        Thread low = new Thread(() -> partial[0] = sum(1, 500000));
        Thread high = new Thread(() -> partial[1] = sum(500001, 1000000));
        low.start();
        high.start();
        low.join();                 // wait for both; join also makes their writes visible
        high.join();
        System.out.println("low half   = " + partial[0]);
        System.out.println("high half  = " + partial[1]);
        System.out.println("total      = " + (partial[0] + partial[1]));
        System.out.println("expected   = " + 1000000L * 1000001 / 2);

        // join(millis) gives up waiting, but does not stop the thread
        Thread slow = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("slow: interrupted, exiting early");
            }
        }, "slow");
        slow.start();
        long t0 = System.nanoTime();
        slow.join(200);
        long waited = (System.nanoTime() - t0) / 1000000;
        System.out.println("join(200) returned after about " + (waited / 100 * 100) + " ms");
        System.out.println("slow is alive: " + slow.isAlive() + ", state " + slow.getState());
        slow.interrupt();           // now ask it to stop, and wait until it has
        slow.join();
        System.out.println("slow is alive: " + slow.isAlive());
    }

    static long sum(long from, long to) {
        long s = 0;
        for (long i = from; i <= to; i++) {
            s += i;
        }
        return s;
    }
}

Output:

Output
low half   = 125000250000
high half  = 375000250000
total      = 500000500000
expected   = 500000500000
join(200) returned after about 200 ms
slow is alive: true, state TIMED_WAITING
slow: interrupted, exiting early
slow is alive: false
  • The two halves, 125,000,250,000 and 375,000,250,000, add up to the expected 500,000,500,000. Each thread writes its own array slot, so they never write the same memory.
  • join does two jobs. It waits, and it guarantees visibility: the Java Memory Model says everything a thread did happens-before another thread returns from join on it. Without the joins, main could read 0 from the array even after the workers finished. The Java Memory Model page explains this rule.
  • join(200) returned after about 200 ms while the thread was still alive in TIMED_WAITING. A timeout does not stop the thread; the program had to interrupt() it and then join() again.

Stopping a thread: interruption

Java has no safe way to kill a thread from outside. Thread.stop released all locks of the victim at an arbitrary point, leaving objects half-updated; it was deprecated in Java 1.2 and throws UnsupportedOperationException since Java 20, as do suspend and resume. Stopping is cooperative instead. interrupt() sets a flag on the target thread, and the target decides when and how to stop. The program shows the four cases that matter.

Java
import java.util.concurrent.atomic.AtomicBoolean;

public class Interruption {

    public static void main(String[] args) throws InterruptedException {
        // 1. A blocked thread: sleep() throws InterruptedException and clears the flag
        Thread sleeper = new Thread(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                boolean flag = Thread.currentThread().isInterrupted();
                System.out.println("1. sleep threw, flag now " + flag);
                Thread.currentThread().interrupt();          // restore it for callers
                flag = Thread.currentThread().isInterrupted();
                System.out.println("1. after restoring, flag " + flag);
            }
        });
        sleeper.start();
        Thread.sleep(100);
        sleeper.interrupt();
        sleeper.join();

        // 2. A busy thread: nothing throws, so it must check the flag itself
        Thread cruncher = new Thread(() -> {
            long n = 0;
            while (!Thread.currentThread().isInterrupted()) {
                n++;
            }
            System.out.println("2. cruncher saw the flag, stopped (counted > 0: " + (n > 0) + ")");
        });
        cruncher.start();
        Thread.sleep(100);
        cruncher.interrupt();
        cruncher.join();

        // 3. Thread.interrupted() reads AND clears the flag of the current thread
        Thread.currentThread().interrupt();
        System.out.println("3. interrupted() first call:  " + Thread.interrupted());
        System.out.println("3. interrupted() second call: " + Thread.interrupted());

        // 4. The trap: swallowing InterruptedException makes the thread unstoppable
        AtomicBoolean reallyStop = new AtomicBoolean();
        Thread stubborn = new Thread(() -> {
            int ignored = 0;
            while (!reallyStop.get()) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    ignored++;                               // empty catch: request lost
                }
            }
            System.out.println("4. stubborn ignored " + ignored + " interrupt(s)");
        });
        stubborn.start();
        Thread.sleep(100);
        stubborn.interrupt();
        Thread.sleep(300);
        System.out.println("4. 300 ms after interrupt(), alive: " + stubborn.isAlive());
        reallyStop.set(true);
        stubborn.join();
    }
}

Output:

Output
1. sleep threw, flag now false
1. after restoring, flag true
2. cruncher saw the flag, stopped (counted > 0: true)
3. interrupted() first call:  true
3. interrupted() second call: false
4. 300 ms after interrupt(), alive: true
4. stubborn ignored 1 interrupt(s)
  1. A thread inside a blocking call (sleep, wait, join, BlockingQueue.take and others) wakes at once with InterruptedException. Throwing it clears the flag, which is why the first line prints false. If you cannot rethrow the exception, call Thread.currentThread().interrupt() to set the flag again so the caller and any loop condition still see the request.
  2. A thread busy computing never blocks, so nothing throws. It must check isInterrupted() at regular points, as the cruncher's loop does. The number of iterations it managed varies between runs, so the program only prints that it was above zero.
  3. Thread.interrupted() is a static method that returns the current thread's flag and clears it. The first call returns true, the second false. isInterrupted() reads without clearing. Mixing them up is a common source of lost interrupts.
  4. The trap: an empty catch swallows the request. The stubborn thread caught the one interrupt, carried on, and was still alive 300 ms later. Only a second mechanism, the reallyStop flag, could end it. In a thread pool, a task like this blocks shutdownNow() forever.

Blocking I/O on java.io streams does not respond to interruption on platform threads. To unblock a thread stuck in a socket read, close the socket; NIO channels that implement InterruptibleChannel are closed automatically when their thread is interrupted.

Uncaught exceptions and daemon threads

An exception thrown out of run ends that thread and nothing else. The program lets two threads fail, one with its own handler and one that falls through to the default handler, and then starts a background heartbeat that never ends by itself.

Java
public class DaemonAndErrors {

    static String config;                                     // never set

    public static void main(String[] args) throws InterruptedException {
        // A default handler catches failures of every thread that has no handler of its own
        Thread.setDefaultUncaughtExceptionHandler((t, e) ->
                System.out.println("default handler: " + t.getName() + " failed: " + e));

        // 1. An exception kills only the thread that threw it
        Thread parser = new Thread(() -> {
            throw new IllegalStateException("bad input on line 3");
        }, "parser");
        parser.setUncaughtExceptionHandler((t, e) ->
                System.out.println("own handler:     " + t.getName() + " died: " + e.getMessage()));
        parser.start();
        parser.join();

        Thread loader = new Thread(() -> {
            System.out.println(config.length());              // NullPointerException
        }, "loader");
        loader.start();
        loader.join();
        System.out.println("main is still running; loader state " + loader.getState());

        // 2. Daemon status is inherited from the creating thread and must be set before start()
        Thread heartbeat = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }, "heartbeat");
        System.out.println("heartbeat daemon by default: " + heartbeat.isDaemon());
        heartbeat.setDaemon(true);
        heartbeat.start();
        try {
            heartbeat.setDaemon(false);
        } catch (IllegalThreadStateException e) {
            System.out.println("setDaemon after start: IllegalThreadStateException");
        }

        // A JVM shutdown hook runs when the last non-daemon thread (main) ends
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
                System.out.println("shutdown hook: heartbeat alive = " + heartbeat.isAlive())));
        System.out.println("main ends now");
    }
}

Output:

Output
own handler:     parser died: bad input on line 3
default handler: loader failed: java.lang.NullPointerException: Cannot invoke "String.length()" because "DaemonAndErrors.config" is null
main is still running; loader state TERMINATED
heartbeat daemon by default: false
setDaemon after start: IllegalThreadStateException
main ends now
shutdown hook: heartbeat alive = true
  • The lookup order for a failed thread is its own UncaughtExceptionHandler, then its thread group, then Thread.setDefaultUncaughtExceptionHandler. With none set, the JVM prints the stack trace to standard error, and the failure is easy to miss in a server log. Set a default handler at start-up that logs properly.
  • "main is still running" shows that main is unaffected; the loader thread is simply TERMINATED. Nothing tells main the work failed unless it checks. Executors and Future solve this by rethrowing the failure when you ask for the result.
  • A new thread copies the daemon flag of the thread that creates it, so threads made by main are non-daemon by default. The flag must be set before start(); changing it afterwards throws IllegalThreadStateException.
  • When main ended, the only remaining thread was the daemon heartbeat, so the JVM began to shut down. Shutdown hooks ran, and the hook still saw the heartbeat alive. Daemon threads are then abandoned mid-step without running finally blocks, so never give them work that must complete, such as writing a file.

What threads cost: platform versus virtual

Each task here sleeps for 100 ms, standing in for a network call, so the ideal time for any number of tasks running together is 100 ms. Anything above that is the cost of creating, scheduling and joining threads. Each count is run 3 times and the fastest run is reported. This is a rough comparison, not a benchmark.

Java
import java.util.ArrayList;
import java.util.List;

public class ThreadCost {

    interface Starter {
        Thread start(Runnable task);
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            try {
                Thread.sleep(100);                  // stands in for a 100 ms network call
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        };
        System.out.println("each thread sleeps 100 ms; times are best of 3 runs");
        measure("platform", 1000, task, t -> Thread.ofPlatform().start(t));
        measure("platform", 10000, task, t -> Thread.ofPlatform().start(t));
        measure("virtual", 10000, task, t -> Thread.ofVirtual().start(t));
        measure("virtual", 100000, task, t -> Thread.ofVirtual().start(t));
    }

    static void measure(String kind, int count, Runnable task, Starter starter)
            throws InterruptedException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            List<Thread> threads = new ArrayList<>(count);
            long t0 = System.nanoTime();
            for (int i = 0; i < count; i++) {
                threads.add(starter.start(task));
            }
            for (Thread t : threads) {
                t.join();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-8s %,8d threads: %,6d ms%n", kind, count, best / 1000000);
    }
}

Output (measured on a 2-CPU Linux machine with JDK 21; your times will differ):

Output
each thread sleeps 100 ms; times are best of 3 runs
platform    1,000 threads:    188 ms
platform   10,000 threads:  1,595 ms
virtual    10,000 threads:    114 ms
virtual   100,000 threads:    257 ms
  • 1,000 platform threads took roughly twice the ideal time, and 10,000 took around 15 times it. Each platform thread is an OS thread with its own stack mapping, and creating 10,000 of them keeps the kernel busy.
  • 10,000 virtual threads finished close to the ideal 100 ms, and even 100,000 took only two to three times that. Sleeping virtual threads give up their carrier, so a handful of carriers serve all of them.
  • Virtual threads make waiting cheap, not computing faster. For CPU-bound work, the number of cores is the limit, and a pool sized to the core count is the right tool. See virtual threads for pinning and other details.

Priorities, sleep and yield

A few Thread methods look like controls but are only hints, and code that depends on them breaks on another machine.

  • setPriority takes 1 to 10, default 5. On Linux, HotSpot ignores priorities unless special flags are set, and the OS scheduler is free to ignore them anyway. A virtual thread's priority is always 5 and setPriority has no effect on it.
  • Thread.sleep(ms) waits at least the given time, possibly more. It does not release locks the thread holds, which makes sleeping inside synchronized a way to stall every other thread that needs the lock.
  • Thread.yield() suggests that the scheduler run another thread. It may do nothing. Thread.onSpinWait() (Java 9) is the right call inside a busy-wait loop; on x86 it emits a PAUSE instruction.

Choosing how to run concurrent work

Which tool to use
SituationUse
A few long-lived background threadsThread.ofPlatform().name(...).start(task)
Many short tasks, CPU-boundA fixed pool: ExecutorService
Many tasks that mostly wait on I/OExecutors.newVirtualThreadPerTaskExecutor()
Tasks that return a result or may failsubmit a Callable and read the Future, or CompletableFuture
Waiting for threads you startedjoin(), or CountDownLatch for many
Passing work between threadsBlockingQueue
Stopping a threadinterrupt(), with the task checking the flag and handling InterruptedException
Housekeeping that may be abandoned at exitA daemon thread

When threads share mutable data, read the Java Memory Model and synchronized and volatile next.