Card 04/ 08

ConceptDifficulty: Intermediate1 min

Thread States: NEW, RUNNABLE, BLOCKED, WAITING and TERMINATED

The word beside each thread in a thread dump, and the one transition that never happens.

A Java thread is always in one of six states, from NEW before it starts to TERMINATED after it ends. A thread dump, a snapshot of every thread in a running program, lists each thread with its current state, and reading those states is most of diagnosing a program that has stopped responding.

A thread dump of a stuck service shows forty threads and a word beside each. There are only six possible words, and they move in one direction:

A thread moves from new to terminated and never goes back
What each state means in a thread dump
StateMeansWaiting for
NEWCreated, never startedNothing: nobody has called start()
RUNNABLEAble to runA processor, or the operating system
BLOCKEDWants a lock somebody else holdsThat lock
WAITINGAsked to be woken laterAnother thread, with no deadline
TIMED_WAITINGThe same, with a deadlineAnother thread, or the clock
TERMINATEDIts run method has returnedNothing; it is finished

Many threads BLOCKED on the same lock point at contention, where one lock is shared by too much work. Many threads WAITING for each other point at a deadlock, where each holds something another needs and none can move.

The arrow that does not exist is the one from TERMINATED back to RUNNABLE. A thread that has finished is finished, and calling start() on it a second time throws IllegalThreadStateException.

So a Thread object is not a worker you hand jobs to. It is one job, run once, and the thing that lets you hand jobs to a reusable worker is a pool.