Card 04/ 08
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:
| State | Means | Waiting for |
|---|---|---|
NEW | Created, never started | Nothing: nobody has called start() |
RUNNABLE | Able to run | A processor, or the operating system |
BLOCKED | Wants a lock somebody else holds | That lock |
WAITING | Asked to be woken later | Another thread, with no deadline |
TIMED_WAITING | The same, with a deadline | Another thread, or the clock |
TERMINATED | Its run method has returned | Nothing; 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.
← → move through sections and cards