Thread Lifecycle in Java
Every Java thread passes through a defined set of states during its lifetime, modeled by the Thread.State enum. Understanding these states helps you interp...
The Six Thread States
Every Java thread passes through a defined set of states during its lifetime, modeled by the Thread.State enum. Understanding these states helps you interpret thread dumps, diagnose concurrency bugs, and reason about application behavior under load. The six states are NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
A thread starts in the NEW state immediately after it is instantiated but before start() is called. No resources have been allocated yet; the JVM simply has an object describing a future thread. Calling start() transitions the thread to the RUNNABLE state, which covers both the waiting-to-be-scheduled and actively-executing sub-states. From the JVM's perspective, a thread is RUNNABLE as long as it is eligible to be scheduled onto a CPU.
The BLOCKED state occurs specifically when a thread is waiting to acquire a monitor lock held by another thread. For example, if Thread A holds a synchronized lock and Thread B tries to enter a synchronized block guarded by that same lock, Thread B moves to BLOCKED until Thread A releases it.
WAITING is a state where a thread has voluntarily paused and will only continue when another thread explicitly notifies it. This happens when a thread calls Object.wait(), Thread.join() with no timeout, or LockSupport.park(). In contrast, TIMED_WAITING is identical but with a maximum wait duration, entered via Thread.sleep(ms), Object.wait(ms), Thread.join(ms), or LockSupport.parkNanos().
You can observe a thread's current state using the getState() method:
Thread t = new Thread(() -> {}); System.out.println(t.getState()); // NEW t.start(); System.out.println(t.getState()); // RUNNABLE or TERMINATED
Finally, once the run() method completes normally or due to an uncaught exception, the thread moves to TERMINATED and can never be restarted.
Interview tip: When asked to distinguish BLOCKED from WAITING, point out that BLOCKED is always about monitor acquisition (synchronized), while WAITING is a deliberate pause that requires an explicit signal from another thread to resume.
Transitions Between States
Thread state transitions in Java are triggered by specific method calls, lock acquisitions, and external events. Mapping these transitions precisely is important when analyzing thread dumps from a production system to identify deadlocked or stuck threads.
From NEW, the only valid transition is to RUNNABLE, triggered by start(). From RUNNABLE, a thread can transition to BLOCKED when it attempts to enter a synchronized block that is already locked by another thread. It returns to RUNNABLE automatically when the lock becomes available and the thread acquires it.
A RUNNABLE thread transitions to WAITING when it calls Object.wait() inside a synchronized block. It transitions back to RUNNABLE when another thread calls notify() or notifyAll() on the same monitor object, provided the waiting thread can reacquire the lock. If the thread calls wait(ms) or sleep(ms), it enters TIMED_WAITING instead and returns to RUNNABLE either when notified or when the timeout elapses.
The join() method illustrates multiple transitions neatly. When Thread A calls threadB.join(), Thread A enters WAITING until Thread B reaches TERMINATED. At that point, Thread A is returned to RUNNABLE.
Example showing state observation:
Thread t = new Thread(() -> { try { Thread.sleep(200); } catch (InterruptedException e) {} }); t.start(); Thread.sleep(50); System.out.println(t.getState()); // TIMED_WAITING t.join(); System.out.println(t.getState()); // TERMINATED
One subtlety is that a thread in RUNNABLE may not actually be executing at any given moment; it may be queued by the OS scheduler. The JVM does not distinguish between queued and executing in the Thread.State enum, which is why thread dumps sometimes show RUNNABLE threads that appear idle.
Understanding these transitions is essential for reading thread dumps correctly. A high number of BLOCKED threads indicates lock contention; a high number of WAITING threads may indicate a producer-consumer imbalance or a missing notification.
Interview tip: Explain the difference between notify() and notifyAll(). notify() wakes up one arbitrary waiting thread, which can cause starvation if other threads never get chosen. notifyAll() wakes all waiting threads, which is safer but may cause a thundering herd if many threads compete for the same resource.
Thread Termination and Cleanup
A thread reaches the TERMINATED state when its run() method returns, either normally after completing all its work or abnormally after an uncaught exception propagates out. Once terminated, a thread cannot be restarted; calling start() on a TERMINATED thread throws IllegalThreadStateException.
Graceful termination is an important design concern for long-running background threads. The recommended pattern is to use a volatile boolean flag that the thread checks periodically:
class Worker extends Thread { private volatile boolean running = true; public void stopWorker() { running = false; } public void run() { while (running) { // do work } } }
The volatile keyword ensures that changes to the flag made by one thread are immediately visible to all other threads. Without volatile, the JVM may cache the flag value in a CPU register, and the worker thread might never see the updated value.
A cleaner alternative to a boolean flag is to use thread interruption. Call interrupt() on the thread, and inside run(), periodically call Thread.currentThread().isInterrupted(). If the thread blocks on sleep() or wait(), those methods will throw InterruptedException, which you catch and use as the signal to exit the loop.
When threads are part of a thread pool managed by ExecutorService, you do not shut down individual threads directly. Instead, you call shutdown() on the pool, which prevents new task submissions and waits for in-progress tasks to complete. For urgent shutdown, shutdownNow() interrupts running threads.
Cleanup code in threads should be placed in a try-finally block inside run() to ensure it executes regardless of how the thread exits:
public void run() { try { doWork(); } finally { releaseResources(); } }
Thread-local variables must also be explicitly cleaned up in the finally block using ThreadLocal.remove(), especially when the thread belongs to a pool that will be reused.
Interview tip: Explain why the deprecated Thread.stop() method is dangerous. It stops a thread by throwing ThreadDeath at an arbitrary point in its execution, potentially leaving shared objects in a partially updated, corrupted state with no way to recover.