skip to content

sleep, join, yield

sleep pauses without releasing any lock, join waits for another thread to finish, and yield is only a hint the scheduler may ignore. The sleep-holds-the-lock detail is the one interviewers most often probe.

part ofJavaread it →
on this pageshow

questions

6

What does Thread.join() do, and when would you use it?

level: juniorimportance: must knowfreq 72%

answer

  1. join = wait for that thread to die
  2. caller blocks in WAITING / TIMED_WAITING
  3. timed join may return early → check isAlive()
  4. join establishes happens-before (results visible)
  5. throws InterruptedException; join(0) = wait forever

basics

~10 s

Calling t.join() makes the current thread wait until thread t finishes before continuing. You use it to make sure a worker thread's work is done before reading its results.

solid answer

~40 s

Thread.join() lets one thread wait for another to terminate. If thread A calls b.join(), A blocks (in WAITING, or TIMED_WAITING if a timeout is given) until thread B's run() completes, by returning or by throwing. In the JDK, join() is built on wait/notify: a dying thread notifies its waiters. The overloads join(millis) and join(millis, nanos) wait at most that long, then return regardless of whether the thread finished — so after a timed join you should check isAlive() to know if it actually completed; join(Duration), added in JDK 19, returns that answer as a boolean. join() throws InterruptedException. Typical use: a main thread spawns workers, then joins each so it can safely read their results, knowing the workers' writes happen-before the join returns. Joining a thread that has already finished returns immediately.

code

java · 11 lines
java
Thread worker = new Thread(() -> {
    // compute something
});
worker.start();

worker.join(2000);            // wait up to 2s
if (worker.isAlive()) {
    // timed out: worker still running
} else {
    // worker finished; its results are safely visible here
}

go deeper

for a junior

Knows t.join() makes the current thread wait until t finishes, used to sequence work.

for a middle

Explains WAITING vs TIMED_WAITING, the timeout overloads + isAlive() check, and that join throws InterruptedException.

for a senior

Articulates the happens-before/memory-visibility guarantee, that join is built on wait/notify, the join(0) gotcha, and that interrupting the joiner doesn't stop the target.

for a principal

Compares raw join to ExecutorService/Future/CompletableFuture/structured concurrency, reasons about cancellation, error propagation, and scaling coordination beyond a handful of threads.

## The problem join solves When you start a thread with `t.start()`, it runs **concurrently** — your code keeps going while the new thread does its work. Often you need to **wait for that thread to finish** before moving on (e.g., to combine its results). `Thread.join()` is exactly that: "block me until that other thread has ended." ## What join does, precisely `t.join()` is an instance method called on a **target thread** `t`. The thread that *calls* it (the caller) is suspended until `t` **terminates** — i.e., `t`'s `run()` method returns or throws, putting `t` in the `TERMINATED` state. While waiting, the caller is in the **`WAITING`** state (or **`TIMED_WAITING`** if you pass a timeout). ```java Thread worker = new Thread(() -> doWork()); worker.start(); worker.join(); // main thread blocks here until worker ends useResultsOf(worker); // safe: worker has finished ``` ## Overloads and the timeout - `join()` — wait **indefinitely** until the thread dies. - `join(long millis)` — wait **at most** `millis`; if the thread is still running when time runs out, `join` simply **returns anyway**. - `join(long millis, int nanos)` — finer-grained timeout. - `join(Duration)` (since JDK 19) — waits at most that long and **returns a boolean**: `true` if the thread has terminated. A zero or negative duration does not wait; it only tests, and an unstarted thread makes it throw `IllegalThreadStateException`. Because a **timed** join can return *before* the thread finishes, you must check **`t.isAlive()`** afterward (or use the boolean from `join(Duration)`) to know whether it actually completed or you just timed out. (A plain untimed `join()` on a started thread means the thread is done when it returns; on a thread that was never started it returns at once.) ## How it works under the hood In the JDK, `join` is implemented with **`wait/notify`** on the thread object. The Javadoc says so in an `@implNote`, so it describes this implementation rather than a promise. The thread's monitor is used internally; when a thread terminates, `notifyAll` is invoked on it, waking any joiners. At JDK 25 the note covers platform threads only, and a virtual thread's join waits another way; at JDK 27 virtual threads use the same loop. Note a subtle pitfall: because `Thread` itself uses its own monitor for `join`, you should **never** call `wait`/`notify` on a `Thread` object yourself — you'd interfere with `join`'s mechanism. ## Memory visibility — a key guarantee `join` establishes a **happens-before** relationship: everything the joined thread did **before it terminated** is **guaranteed visible** to the caller **after** `join` returns. So you can read the worker's results without extra synchronization. This is one of the main reasons join is safe and useful, not just convenient. ## Interruption `join` throws **`InterruptedException`**: another thread can `interrupt()` the waiter to make it stop waiting early. You must handle or propagate that checked exception. Interrupting the *joiner* does not stop the *target* thread — it only ends the wait. ## Edge cases - Joining a thread that **already finished** returns immediately. - Joining a thread that was **never started** also returns immediately from `join()` and `join(long)` (it's considered not alive); `join(Duration)` throws `IllegalThreadStateException` instead. - `join(0)` means "wait forever," the same as `join()` (0 = no timeout, not zero wait), while `join(Duration.ZERO)` does not wait at all. ## Modern alternatives For coordinating *many* tasks, raw `join` gets clumsy. Prefer `ExecutorService` + `Future.get()`, `CompletableFuture`, `CountDownLatch`, or **structured concurrency** (`StructuredTaskScope`, still a preview API at JDK 27), which joins a whole group of tasks cleanly.

  • After t.join(5000) returns, how do you know whether t actually finished?
    Check t.isAlive(). A timed join returns when the thread dies OR when the timeout elapses, so isAlive() distinguishes 'finished' (false) from 'timed out, still running' (true). Since JDK 19, t.join(Duration.ofSeconds(5)) returns that answer directly as a boolean.
  • Does join() guarantee you can safely read data the joined thread wrote?
    Yes. join establishes a happens-before edge: all writes the thread made before terminating are visible to the caller after join returns, so no extra synchronization is needed to read those results.

  • Thinking join() stops or kills the target thread — it only waits for it to finish naturally.
  • Assuming a timed join() means the thread finished — it may have just timed out; check isAlive().
  • Believing join(0) waits zero time — 0 means wait indefinitely.
  • Forgetting the happens-before visibility guarantee and adding redundant synchronization, or worse, reading results before joining.

Thread.join(Duration) returning a boolean
Java 19

Assumes JDK 27. join(Duration), which returns a boolean, exists since JDK 19, so 25 has it too; the wait/notify implementation note covers virtual threads at 27 but only platform threads at 25.

context

open as a page

What does Thread.sleep() do, and how does it differ from Object.wait() regarding locks?

level: juniorimportance: must knowfreq 78%

basics

~10 s

Thread.sleep() pauses the current thread for a given time but keeps any locks it holds. wait() also pauses the thread but releases the lock on the object so other threads can use it.

open as a page

What makes Thread.sleep() and Thread.join() throw InterruptedException, and which thread has to be interrupted for each?

level: middleimportance: must knowfreq 58%

basics

~20 s

Thread.sleep() and Thread.join() throw InterruptedException when the calling thread is interrupted while it waits, and clear its interrupt status; for join(), that means the waiter, not the target. Never swallow it: propagate it or restore the flag.

open as a page

Do Thread.sleep and Thread.yield have memory effects, and why can a loop polling a plain field with sleep() never see the update?

level: middleimportance: should knowfreq 52%

basics

~20 s

Thread.sleep and Thread.yield have no synchronization semantics in the JLS, so the compiler may read a non-volatile field once and reuse that value, and a polling loop may never end. Use a volatile field or a blocking hand-off.

open as a page

What is Thread.yield(), and why is it rarely the right tool?

level: middleimportance: should knowfreq 48%

basics

~20 s

Thread.yield() is a hint that the current thread is willing to give up the CPU so other threads can run. The scheduler is free to ignore it, so it guarantees nothing and is rarely needed.

open as a page

How do Java thread priorities work, and how much should you rely on them?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

You can set a thread's priority from 1 to 10 (default 5) as a hint that it should get more CPU time. But priorities are advisory and depend on the OS, so you should not rely on them for correctness.

open as a page