Thread states and daemon threads
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every Java thread moves through a small set of states, from created to finished, and you can ask a thread which state it is in. Two settings, daemon and priority, change how the JVM and the scheduler treat it.
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
A daemon thread is a background thread that does not keep the program alive; the JVM exits when only daemon threads are left.
A thread state is where a thread is in its life, from creation to finish. Java names six states in the enum Thread.State, and a thread is in exactly one of them at any moment.
Example 1 · The six states
public class StatesListDemo { public static void main(String[] args) { for (Thread.State s : Thread.State.values()) { System.out.println(s.ordinal() + " " + s); } Thread t = new Thread(() -> { }, "fresh"); System.out.println("A new thread is " + t.getState()); }}0 NEW 1 RUNNABLE 2 BLOCKED 3 WAITING 4 TIMED_WAITING 5 TERMINATED A new thread is NEW
What this code does
Thread.Stateis an ordinary enum, sovalues()lists its six constants in order.- A thread object that has not been started is always
NEW; nothing runs untilstart().
- NEW: created with
new Thread(...),start()not called yet. - RUNNABLE: started and able to run. Java uses one state for both "running on a core now" and "ready, waiting for a core".
- BLOCKED: waiting to enter a
synchronizedblock that another thread is inside (the Race Conditions module covers it). - WAITING: waiting with no time limit, for example in
join()orwait(). - TIMED_WAITING: waiting with a time limit, for example in
sleep(ms)orjoin(ms). - TERMINATED:
run()has finished, normally or with an exception. It never changes again.
Checking a state with getState()
getState() returns the thread's current Thread.State. It is a snapshot: by the time you print it, the thread may already have moved on. Use it for logging, debugging and learning, not to decide what your program does.
Example 2 · Tracing one thread through its life
public class LifeCycleDemo { static void pause(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { Thread mainThread = Thread.currentThread(); String[] seen = new String[1];
Thread worker = new Thread(() -> { pause(150); // TIMED_WAITING while sleeping seen[0] = mainThread.getState().toString(); // main is inside join() now }, "worker");
System.out.println("before start : " + worker.getState()); worker.start(); System.out.println("main itself : " + mainThread.getState()); pause(50); System.out.println("while sleeping: " + worker.getState()); worker.join(); System.out.println("main in join : " + seen[0]); System.out.println("after join : " + worker.getState());
Thread spinner = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { // busy work, never waits } }, "spinner"); spinner.start(); pause(20); System.out.println("busy spinner : " + spinner.getState()); spinner.interrupt(); spinner.join(); }}before start : NEW main itself : RUNNABLE while sleeping: TIMED_WAITING main in join : WAITING after join : TERMINATED busy spinner : RUNNABLE
What this code does
- A thread checking itself is always
RUNNABLE, because it is running. The worker, checked frommainwhile it sleeps, isTIMED_WAITING;main, checked by the worker whilemainsits injoin(), isWAITING. - Each check is a snapshot that depends on timing. On a normal run you get exactly these states, but on a very busy computer a check could catch a thread a moment earlier or later, so this is a sample.
A usual life looks like this: NEW → start() → RUNNABLE, then back and forth between RUNNABLE and the waiting states while it sleeps, joins or waits for a lock, and finally TERMINATED. A thread never goes back to NEW, which is why it cannot be started twice.
Daemon threads and when the JVM exits
A daemon thread is a background helper that does not keep the program alive. The JVM exits when every non-daemon thread (also called a user thread) has finished. Daemon threads still running at that moment are stopped abruptly, and their finally blocks do not run.
Example 3 · A daemon autosave thread is cut off
public class DaemonDemo { public static void main(String[] args) throws InterruptedException { Thread autosave = new Thread(() -> { int draft = 0; try { while (true) { Thread.sleep(40); draft++; System.out.println("autosave: saved draft " + draft); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { System.out.println("autosave: closing the file"); // never printed here } }, "autosave"); autosave.setDaemon(true); // must come before start() autosave.start();
System.out.println("main: editing notes, autosave is daemon = " + autosave.isDaemon()); Thread.sleep(150); System.out.println("main: done, the JVM can exit now"); }}main: editing notes, autosave is daemon = true autosave: saved draft 1 autosave: saved draft 2 autosave: saved draft 3 main: done, the JVM can exit now
What this code does
mainis the only user thread. When it returns, the JVM exits even thoughautosaveis insidewhile (true). WithoutsetDaemon(true)this program would never end.- The
finallyblock never prints: daemon threads are stopped abruptly when the JVM exits. The number of drafts depends on timing (usually 3), so the output is a sample.
Example 4 · setDaemon after start, and inherited settings
public class DaemonRulesDemo { public static void main(String[] args) throws InterruptedException { Thread late = new Thread(() -> { }, "late"); late.start(); try { late.setDaemon(true); } catch (IllegalThreadStateException e) { System.out.println("setDaemon after start: " + e.getClass().getSimpleName()); } late.join();
boolean[] childIsDaemon = new boolean[1]; Thread cleaner = new Thread(() -> { Thread child = new Thread(() -> { }, "cleaner-child"); // created by a daemon childIsDaemon[0] = child.isDaemon(); }, "cache-cleaner"); cleaner.setDaemon(true); cleaner.start(); cleaner.join();
System.out.println("main is daemon: " + Thread.currentThread().isDaemon()); System.out.println("cache-cleaner is daemon: " + cleaner.isDaemon()); System.out.println("its child is daemon: " + childIsDaemon[0]); }}setDaemon after start: IllegalThreadStateException main is daemon: false cache-cleaner is daemon: true its child is daemon: true
What this code does
- The daemon setting is fixed once the thread is alive, so
setDaemonafterstart()throwsIllegalThreadStateException. mainis a user thread, so threads it creates are user threads by default.cleaner-childwas created by a daemon thread, so it starts as a daemon too.
Call setDaemon(true) before start(); after start() it throws IllegalThreadStateException. A new thread starts with the daemon setting of the thread that created it, and main is not a daemon, so your threads are user threads unless you say otherwise. Use daemon threads only for work that may be dropped at any moment, such as a cache cleaner or a heartbeat. Never use them for saving files, payments or anything that must finish.
Priorities are only hints
A thread's priority is a number from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY); the default is 5 (Thread.NORM_PRIORITY), and a new thread starts with its creator's priority. setPriority outside 1–10 throws IllegalArgumentException.
Example 5 · Priorities: values and limits
public class PriorityDemo { public static void main(String[] args) { System.out.println("MIN=" + Thread.MIN_PRIORITY + " NORM=" + Thread.NORM_PRIORITY + " MAX=" + Thread.MAX_PRIORITY); System.out.println("main priority: " + Thread.currentThread().getPriority());
Thread report = new Thread(() -> { }, "report"); System.out.println("report starts with: " + report.getPriority()); report.setPriority(Thread.MAX_PRIORITY); System.out.println("report after setPriority: " + report.getPriority());
try { report.setPriority(11); } catch (IllegalArgumentException e) { System.out.println("setPriority(11): " + e.getClass().getSimpleName()); } }}MIN=1 NORM=5 MAX=10 main priority: 5 report starts with: 5 report after setPriority: 10 setPriority(11): IllegalArgumentException
What this code does
- Priorities run from 1 to 10.
reportstarts with its creator's priority, 5, and anything outside 1–10 is rejected. - Setting 10 only changes a hint. It does not promise that
reportruns first or finishes sooner; on some systems it makes no visible difference.
Priority is only a hint to the scheduler. Some operating systems ignore it and others treat it differently, so a high-priority thread is not guaranteed to run first or faster. Never rely on priorities for correctness; use join and the coordination tools of later modules instead.
Next step
Check your understanding
12 quick questions