Java Materials
← Core Java · Chapter 11

Threads, lifecycle and cancellation

A process owns resources and address space. A platform thread maps to an OS thread in typical HotSpot deployments; the OS schedules runnable threads on CPU cores. A context switch changes which execution state runs. Thread implements execution of a Runnable, while Callable returns a value and can declare checked failures through an executor.

Lifecycle and interpreting thread dumps

Definition:

A Java thread state describes execution or waiting from the JVM’s perspective.

Explanation:

A Java RUNNABLE state is not direct proof of CPU consumption; it can also appear during native activity.

Illustration image:

Lifecycle and interpreting thread dumps. NEW · RUNNABLE · BLOCKED or WAITING · TERMINATEDLifecycle and interpreting thread dumpsSource or actorNEWFirst boundaryRUNNABLEInspected stateBLOCKED or WAITINGObservable effectTERMINATED
NEW · RUNNABLE · BLOCKED or WAITING · TERMINATED

Example:

Worked Java example · see surrounding context in notes
Thread t = new Thread(() -> System.out.println("worker"), "example-worker");
System.out.println(t.getState()); // NEW
t.start();
t.join();
System.out.println(t.getState()); // TERMINATED

Expected behavior. join establishes an observation boundary; do not assert an intermediate state with a sleep.

Internal working:

BLOCKED denotes intrinsic monitor acquisition, while a thread parked by a ReentrantLock commonly appears WAITING. Compare several dumps and CPU samples. Inspect lock identity and owning thread instead of diagnosing from names alone.

Interview questions:

Does RUNNABLE mean a thread is consuming CPU?

No. It can also be eligible to run or in a native operation. Compare stacks and CPU samples.

Interrupt handling and shutdown handshake

Definition:

A shutdown handshake requests cancellation and checks that the worker actually stopped.

Explanation:

Cancellation is cooperative.

Illustration image:

Interrupt handling and shutdown handshake. Caller interrupts · Worker releases resources · Caller joins with deadline · Check isAliveInterrupt handling and shutdown handshakeSource or actorCaller interruptsFirst boundaryWorker releases resourcesInspected stateCaller joins with deadlineObservable effectCheck isAlive
Caller interrupts · Worker releases resources · Caller joins with deadline · Check isAlive

Example:

Worked Java example · see surrounding context in notes
worker.interrupt();
worker.join(1000);
if (worker.isAlive()) recordShutdownTimeout();

Expected behavior. A successful return from the timed join alone does not prove termination.

Internal working:

Blocking calls such as BlockingQueue.take respond to interruption; other I/O has different timeout and cancellation behavior. Do not hold a resource the worker needs while joining it. Prefer a bounded shutdown deadline and tell monitoring when a worker did not terminate.

Interview questions:

What does join(1_000) prove when it returns?

Only that the wait ended. Check isAlive to distinguish completion from timeout.

Thread ownership and exception visibility

Definition:

Task failure observation depends on whether execution exposes a thread failure or a Future result.

Explanation:

Thread naming, daemon policy and handlers are operational choices.

Illustration image:

Thread ownership and exception visibility. Executor submit · Task throws · Future stores failure · get reports causeThread ownership and exception visibilitySource or actorExecutor submitFirst boundaryTask throwsInspected stateFuture stores failureObservable effectget reports cause
Executor submit · Task throws · Future stores failure · get reports cause

Example:

Worked Java example · see surrounding context in notes
var executor = java.util.concurrent.Executors.newSingleThreadExecutor();
try {
    var task = executor.submit(() -> { throw new IllegalStateException("failed"); });
    task.get();
} finally {
    executor.shutdown();
}

Expected behavior. get throws ExecutionException with the task failure as its cause.

Internal working:

Executor submit wraps exceptions in a Future; an uncaught-exception handler is not a universal task observer. Centralize result consumption and avoid application life-cycle dependencies on daemon threads that can disappear during JVM shutdown.

Interview questions:

Why might a thread’s uncaught handler miss an exception from submit?

submit wraps the task outcome. Read the Future or observe the failure through executor instrumentation.

Reference subtopics

Start, join and six states

start schedules a new thread; calling run runs inline. NEW is unstarted, RUNNABLE covers eligible or executing work, BLOCKED means waiting to enter a monitor, WAITING is indefinite waiting, TIMED_WAITING is bounded waiting and TERMINATED is finished. A dump can show RUNNABLE in native I/O; use stacks and CPU samples to interpret it.

Waiting and lock ownership

sleep does not release held monitors. wait requires ownership of its target monitor and releases that monitor while waiting. join waits for another thread's completion without releasing arbitrary locks held by the caller; avoid joining while holding locks that task needs. LockSupport.park does not release arbitrary locks and can return spuriously.

Names, daemon status and failure reporting

ThreadFactory centralizes naming and policy. Daemon threads do not keep the JVM alive, so do not rely on them for durable cleanup. An uncaught-exception handler sees uncaught thread failures; executor submit usually captures them in a Future, which must be observed separately.

Cooperative cancellation

interrupt sets a flag or wakes certain operations. isInterrupted reads without clearing; Thread.interrupted reads and clears the current flag. Future.cancel(true) requests interruption when supported but does not forcibly stop the work. A worker must respond, release resources and leave. Race, deadlock, livelock and starvation describe different failures; confinement avoids sharing mutable state in the first place.

Run the complete Java labs ↗ · Java reference ↗