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
- 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
option, or-Xss = 1024 KB). Creating one is a system call, so thousands are fine and hundreds of thousands are not.ThreadStackSize - 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 mainSystem.exit
| Approach | Since | Best for |
|---|---|---|
Subclass Threadrun | Java 1.0 | Rarely the right choice; it mixes the task with how it is run |
new Thread(Runnable, name) | Java 1.0 | A few long-lived platform threads in older code |
Thread.ofPlatform() | Java 21 | Platform threads with names, daemon flag or stack size set in one place |
Thread.ofVirtual()Thread.startVirtualThread | Java 21 | Many tasks that spend most of their time waiting |
ExecutorService | Java 5 | Most 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.
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:
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
: a method with no arguments and no result, usually written as a lambda. Passing aRunnable keeps the task independent, so the same lambda can later go to an executor or a virtual thread unchanged. That is why subclassingRunnable is discouraged.Thread numbers the threads it creates: pool-1, pool-2, pool-3. A builder'sThread.ofPlatform().name("pool-", 1) gives afactory() , which is what executors accept. Threads fromThreadFactory are created in statenewThread and are not running yet.NEW- The virtual thread reports
andisVirtual=true . Virtual threads are always daemon threads, and callingdaemon=true on one throwssetDaemon(false) .IllegalArgumentException - "run() executes in main" is the first trap.
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.run() - The second trap: a
object can be started once. CallingThread again throwsstart() , even after the thread has finished. To repeat the work, create a new thread or use an executor.IllegalThreadStateException
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()getId()
The six thread states
getState()Thread.Statewait()synchronizedmain
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:
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
| State | Meaning | Typical cause |
|---|---|---|
NEW | Created, not started | Before start() |
RUNNABLE | Running, or ready and waiting for a CPU | Executing code, including blocking socket and file I/O |
BLOCKED | Waiting to enter a synchronized | Another thread holds that monitor |
WAITING | Waiting with no time limit | wait()join()LockSupport.park()Lock.lock() |
TIMED_WAITING | Waiting with a time limit | sleep(ms)wait(ms)join(ms)parkNanos |
TERMINATED | Finished | run |
- The waiting thread is
, notWAITING :BLOCKED releases the monitor and parks until notified. The third thread iswait() because it has not entered the monitor at all. WhenBLOCKED callsmain and leaves its block, both can proceed.notifyAll - Only
producessynchronized . A thread waiting for aBLOCKED shows asReentrantLock , because locks inWAITING are built onjava.util.concurrent . Keep that in mind when reading a thread dump.LockSupport.park - A thread blocked in a socket read is
from the JVM's point of view, even though it uses no CPU.RUNNABLE
The short sleeps in mainjoin
Waiting for a thread: join
join()join
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:
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.
does two jobs. It waits, and it guarantees visibility: the Java Memory Model says everything a thread did happens-before another thread returns fromjoin on it. Without the joins,join could read 0 from the array even after the workers finished. ThemainJava Memory Model page explains this rule. returned after about 200 ms while the thread was still alive injoin(200) . A timeout does not stop the thread; the program had toTIMED_WAITING it and theninterrupt() again.join()
Stopping a thread: interruption
Java has no safe way to kill a thread from outside. Thread.stopUnsupportedOperationExceptionsuspendresumeinterrupt()
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:
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)
- A thread inside a blocking call (
,sleep ,wait ,join and others) wakes at once withBlockingQueue.take . Throwing it clears the flag, which is why the first line prints false. If you cannot rethrow the exception, callInterruptedException to set the flag again so the caller and any loop condition still see the request.Thread.currentThread().interrupt() - A thread busy computing never blocks, so nothing throws. It must check
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.isInterrupted() is a static method that returns the current thread's flag and clears it. The first call returns true, the second false.Thread.interrupted() reads without clearing. Mixing them up is a common source of lost interrupts.isInterrupted()- The trap: an empty
swallows the request. The stubborn thread caught the one interrupt, carried on, and was still alive 300 ms later. Only a second mechanism, thecatch flag, could end it. In a thread pool, a task like this blocksreallyStop forever.shutdownNow()
Blocking I/O on java.ioInterruptibleChannel
Uncaught exceptions and daemon threads
An exception thrown out of run
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:
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
, then its thread group, thenUncaughtExceptionHandler . 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.Thread.setDefaultUncaughtExceptionHandler - "main is still running" shows that
is unaffected; the loader thread is simplymain . Nothing tellsTERMINATED the work failed unless it checks. Executors andmain solve this by rethrowing the failure when you ask for the result.Future - A new thread copies the daemon flag of the thread that creates it, so threads made by
are non-daemon by default. The flag must be set beforemain ; changing it afterwards throwsstart() .IllegalThreadStateException - When
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 runningmain blocks, so never give them work that must complete, such as writing a file.finally
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.
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):
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
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 andsetPriority has no effect on it.setPriority waits at least the given time, possibly more. It does not release locks the thread holds, which makes sleeping insideThread.sleep(ms) a way to stall every other thread that needs the lock.synchronized suggests that the scheduler run another thread. It may do nothing.Thread.yield() (Java 9) is the right call inside a busy-wait loop; on x86 it emits aThread.onSpinWait() instruction.PAUSE
Choosing how to run concurrent work
| Situation | Use |
|---|---|
| A few long-lived background threads | Thread.ofPlatform().name(...).start(task) |
| Many short tasks, CPU-bound | A fixed pool: |
| Many tasks that mostly wait on I/O | Executors.newVirtualThreadPerTaskExecutor() |
| Tasks that return a result or may fail | submitCallableFuture |
| Waiting for threads you started | join() |
| Passing work between threads | |
| Stopping a thread | interrupt()InterruptedException |
| Housekeeping that may be abandoned at exit | A daemon thread |
When threads share mutable data, read