Lesson · Multithreading Fundamentals
Thread API: sleep, join, interrupt and the flag that survives
16 min readThread API
Three calls carry most of the coordination between threads. sleep parks the thread that calls it, join parks the caller until another thread dies, and interrupt asks another thread to stop. The first two are certain; the third works by setting a flag, and everything about shutting a thread down politely follows from how that flag is delivered, cleared and restored.
The calls you will actually use
Thread has a large API and a small working surface: start, the blocking waits, and the interrupt flag. Most bugs described as threads hanging come back to the handful of calls in the table below.
Read the middle column as the state of the thread that makes the call, and the last column as the only thing that unparks it.
| Call | Calling thread's state | What it releases | Ends when |
|---|---|---|---|
| t.start() | RUNNABLE (the new thread) | nothing | returns immediately; run() executes on the new thread |
| t.run() | unchanged: still the caller | nothing | the method returns; no thread was created |
| Thread.sleep(ms) | TIMED_WAITING | nothing: monitors stay held | at least ms (best effort), or an InterruptedException |
| t.join() | WAITING | nothing of its own | t terminates |
| t.join(ms) | TIMED_WAITING | nothing of its own | t terminates, or the deadline passes |
| wait() on a monitor | WAITING | the monitor it was called on | notify or notifyAll (a timeout or an interrupt also end it) |
sleep parks the current thread, join parks the caller, and interrupt only moves a flag. Keep those three contracts apart and every waiting bug has a shape.
sleep and join, precisely
Thread.sleep(ms) puts the current thread into TIMED_WAITING for at least that long. The pause is best effort: system timers and scheduling decide the overshoot, so sleep is a pacing tool, never a clock. It cannot return early either; only an interrupt cuts it short.
The guarantee that surprises people is about locks: sleep keeps them. The javadoc is explicit that the sleeping thread does not lose ownership of any monitors, so a thread asleep inside a synchronized block blocks every thread that wants that monitor for the whole nap. wait does the opposite on purpose, and that difference is the reason both calls exist.
join() is the other half: it parks the caller until the target terminates. join() waits as long as it takes (WAITING); join(ms) waits up to a deadline (TIMED_WAITING) and then returns anyway, so check isAlive() when the outcome matters. Join a list of workers in a loop and you have the fork-join shape at thread level.
- sleep holds the monitor; wait releases it. If a lock you hold while parked blocks everyone else, sleep is the wrong call.
- Timing is a target, not a promise. Do not build ordering, deadlines or retries on sleep durations.
- join is also a visibility barrier. A thread's termination happens-before a successful join on it, so everything the worker wrote is readable afterwards (forward link: the memory model).
- join(timeout) returns on the clock, not on death. Distinguish a finished worker from a slow one with isAlive().
sleep holds the monitor; wait releases it. The single sentence behind half of all wait/notify confusion.
interrupt(): one flag, three destinations
interrupt() is not a command. It sets the target's interrupt flag and returns; what happens next depends entirely on where the target is when the flag arrives. There are two destinations: a blocking call that throws on its behalf, or the flag itself, waiting to be read.
If the target is inside sleep, wait or join, it wakes with an InterruptedException, and the exception is delivered at the cost of the flag: the interrupt status is cleared as the throw happens. If the target is running ordinary code, nothing is thrown. The flag simply stays set until something reads it.
The two readers differ in a way that bites: isInterrupted() reports the flag and leaves it alone, while the static Thread.interrupted() reports it and clears it, always for the current thread. Code that calls the static form inside a loop eats its own cancellation.
// One flag, two readers, one of them destructive. worker.isInterrupted(); // reports; the flag is unaffected Thread.interrupted(); // reports AND clears; always about the CURRENT thread while (!Thread.currentThread().isInterrupted()) { // the polling loop doOneUnitOfWork(); }
Interrupt is a request, not a command: the target decides when to stop.
Worker timeline · interrupt flag
starts the worker, then sleeps 500 ms
pass 1: uploading a batch
current call
main → worker.start()
Scene A opens with the naive worker: ordinary work in a loop, a one second sleep between passes, and a catch block about to lose a request. Its loop does test the flag; the trouble starts below.
The interrupt discipline
The throw from sleep is the moment the flag and the exception coexist, and the exception wins: the flag was cleared so the InterruptedException could exist. A catch block that logs and continues has now answered the request with no, and a loop that tests the flag will read false from then on.
The discipline is a two line policy. Either restore the flag with Thread.currentThread().interrupt() and exit, or propagate the InterruptedException and let the caller decide. Swallowing it is the one move that turns a cancelled task into a task that runs to completion.
// WRONG: consumes the request, keeps working. while (running) { try { Thread.sleep(1000); } catch (InterruptedException e) { log.warn("interrupted", e); // the flag was already cleared by the throw continue; // the request is now deleted } work(); } // RIGHT: restore the flag, then leave on your own terms. while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // hand the news back to the loop break; // the exit point belongs to this thread } work(); } cleanup(); // flush, close, commit: this is why cancellation is cooperative
- Poll at the top of the loop with
while (!Thread.currentThread().isInterrupted()), so a flag set between iterations is seen on the next one. - Restore or rethrow in the catch.
Thread.currentThread().interrupt()keeps the status for callers; declaringthrows InterruptedExceptionhands the decision up the stack. - Clean up before returning. The chosen exit point is what makes the flush, the close and the commit possible at all.
- Document the contract. If your method can be cancelled, say so and keep the promise (forward link: exception best practices).
Restore the flag or propagate the exception, never swallow.
What interruption cannot reach
Interruption reaches exactly two places: the flag its owner reads, and the blocking calls that throw for it. Everything else is deaf by design, and the cases below are worth knowing by heart.
- Blocked on a monitor (BLOCKED). Waiting to enter a synchronized block is not an interruptible wait: the flag is set and the thread keeps waiting for the lock.
ReentrantLock.lockInterruptibly()andtryLockexist for acquisition that must cancel (forward link: locks). - Classic socket I/O. A read on a java.io socket does not wake because a flag changed. Give the read a deadline with
setSoTimeout, or close the socket from the interrupting side. NIO channels differ: interrupting an interruptible channel closes it and throws ClosedByInterruptException. - A compute loop with no check. No blocking call can throw and no instruction reads the flag, so the interrupt changes nothing. If the loop can run long, put a poll around each pass, or a volatile cancellation flag when the loop belongs to someone else.
- A thread that is not alive. Interrupting a thread that has not been started or has already died need not do anything; the write lands where no code will read it.
Interruption only works where a flag gets read or a blocking call can throw. Everywhere else it is a note pinned to a wall.
Cooperative cancellation
interrupt() moves a flag; it never moves the thread
main thread
worker.interrupt()
One boolean is written on the target. The caller is done at this point.
target thread
interrupt flag: SET
Delivery depends on what the target is doing when the flag lands.
Where the flag can land
blocked in sleep, wait or join
The blocking call wakes with InterruptedException, and the throw clears the flag as it is delivered.
interrupted, flag clearedpolling the flag in a loop
Nothing is thrown; the next isInterrupted() read sees true and the loop exits on its own terms.
clean exit, cleanup runsnever checking, never blocking
No read and no throwing call ever happens, so the flag just stays set. A busy CPU loop cannot be interrupted.
nothing happensThe flag travels and the thread is never forced: two of the three lanes are the target choosing to stop, and the third is the target never hearing the request at all.
stop, suspend, resume: the methods that had to go
Before cooperative cancellation the platform shipped stop(), suspend() and resume(), and all three are broken in ways no implementation can repair. stop() caused the target to throw ThreadDeath at an arbitrary instruction, and every monitor the target held was released as the death propagated, so other threads could observe objects mid-update.
suspend() froze a thread while it held locks, and nothing forced it to let go, so every thread that wanted those locks parked with it. resume() could not help a target suspended inside an input operation. The deprecations date from Java 1.2 and the methods are now marked for removal; current JDKs make them throw UnsupportedOperationException instead of doing what their names say.
What replaced them is the rest of this topic: a flag for control, exceptions for reporting, and interruptible acquisition in the lock API for the cases monitor entry cannot cover.
| Legacy call | Why it cannot be made safe | What replaced it |
|---|---|---|
| stop() | Kills at an arbitrary instruction and releases monitors mid-update, so damaged objects become visible to others | a cancellation flag plus interrupt; the target returns from run() in an orderly way |
| suspend() / resume() | Freezes a thread that may hold locks, so every waiter is stuck behind a frozen owner | the wait protocol, LockSupport.park/unpark, or a state flag |
| any forced stop | Correctness depends on the instruction pointer at the moment of the kill, which no target code can observe or repair | interruption: the target decides, at a point it owns |
Interruption is cooperative because the only safe stop point is one the target code chooses.
Priorities, yield and the tiny spin
Thread priorities run from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5 as NORM_PRIORITY, and setPriority is a request to the operating system. Most platforms map priorities coarsely, some ignore the mapping, and the value is clamped to the thread group's maximum. No correctness claim may rest on one.
Thread.yield() is the same kind of request: a hint that the caller is willing to give up the processor, which the scheduler is free to ignore. It was never a fairness tool and never a synchronization barrier.
Thread.onSpinWait() (Java 9) is the honest primitive for very short spin loops. It tells the runtime the caller is busy-waiting, and the JVM may emit a CPU hint (a PAUSE instruction on x86) so the pipeline is less wasteful. The loop still needs a volatile flag, because onSpinWait synchronizes nothing.
- Priorities are hints, not guarantees. A high priority thread that never blocks can starve everything below it, which is the incident pattern behind the starvation topic (forward link: starvation and fairness).
- yield cannot fix a race or grant fairness. If you need ordering or exclusivity, reach for a lock; yield offers neither.
- onSpinWait is for the shortest spins only. Beyond a moment, park the thread: burning a core to avoid a context switch is a bad trade at any meaningful duration.
Priorities and yield negotiate with the scheduler; only locks and flags carry contracts.
The interruption you swallowed is gone
When sleep throws InterruptedException, the throw cleared the flag to deliver itself. A catch block that logs and continues has consumed the request and answered it with no, and the while (!isInterrupted()) loop now reads false forever. Restore the flag with Thread.currentThread().interrupt(), or let the exception travel. Swallowing turns a cancelled task into a task that runs to completion.
Interview angles
What is the difference between sleep and wait?+
sleep parks the current thread for a duration and keeps every lock it holds; wait releases the monitor it was called on and returns only when notified, interrupted, or timed out. One is a pause, the other is a release-and-wait protocol.
The javadoc for sleep is one sentence long on this point: the thread does not lose ownership of any monitors. wait requires ownership, which is why it must be called from within a synchronized block.
Follow-up: Why must wait be called while holding the monitor, when sleep has no such requirement?
Does interrupt stop a thread?+
No. It sets the target's flag; if the target is in sleep, wait or join it wakes with InterruptedException and the flag is cleared by the throw. Otherwise the flag stays set and the target must poll it. Cancellation is cooperative by construction.
Common misconception: The name suggests a signal that halts execution. A thread that never blocks and never checks the flag is not affected at all, and this is why CPU bound loops need their own poll.
isInterrupted() or Thread.interrupted(): what is the difference?+
isInterrupted() is an instance method that reports the flag and does not change it. Thread.interrupted() is static, reports and clears the flag, and always means the current thread. The clearing version can destroy a cancellation by accident.
What happens when you interrupt a thread blocked waiting to enter a synchronized block?+
The flag is set and the thread stays BLOCKED until the monitor frees. Monitor entry is not an interruptible wait, so a cancellation cannot reach it; use ReentrantLock.lockInterruptibly() or tryLock when the acquisition must be cancellable.
The same cut applies to classic socket reads: they do not observe interrupts, so the fix is a timeout (setSoTimeout) or closing the socket from the interrupting side. NIO interruptible channels are the exception, because interrupting them closes the channel and throws ClosedByInterruptException.
Why were stop(), suspend() and resume() deprecated?+
stop() threw ThreadDeath into the target at an arbitrary instruction and released its monitors as the error propagated, so other threads could see objects mid-update; suspend() froze a thread while it held locks and deadlocked every waiter. Neither can be made safe, so modern JDKs throw UnsupportedOperationException.
How do you shut a long running CPU bound worker down cleanly?+
Give the loop a cancellation flag it polls every pass, and keep the flag thread safe (interrupt status qualifies, as does a volatile boolean or an AtomicBoolean). If the loop also sleeps or waits, interrupt covers the parked phases, and both paths should exit through one cleanup block.
For a spin that lasts microseconds, Thread.onSpinWait() (Java 9) is the right primitive: it hints the hardware that the loop is intentional. For anything longer, the spin should become a park, because a spinning thread is a core other work cannot use.
Follow-up: How is join implemented on top of wait, and what does that tell you about interrupting the joiner?