Java Thread Join
The Java thread join() method makes one thread wait until another thread has finished. When main calls worker.join(), main pauses on that line and continues only after worker has terminated.
You use join() whenever the next step depends on the result of other threads: open a file after it has downloaded, add up partial results after every worker is done, or shut down cleanly after background tasks complete.
Java Thread join() Syntax
join() is an instance method: you call it on the thread you want to wait for. The calling thread is the one that waits.
thread.join() // wait until thread terminates, no time limit
thread.join(long millis) // wait at most millis milliseconds
thread.join(long millis, int nanos)
boolean done = thread.join(Duration timeout) // Java 19+, returns true if it finished
| Method | Returns | Waiting state of the caller |
|---|---|---|
join() | void | WAITING |
join(millis) / join(millis, nanos) | void | TIMED_WAITING |
join(Duration) | boolean: true if the thread terminated | TIMED_WAITING |
Every form throws InterruptedException if the waiting thread is interrupted. join(0) means "wait forever", the same as join().
The Problem join() Solves
Without join(), main keeps running while the worker is still busy. Here main tries to use a file that has not been downloaded yet.
public class WithoutJoin {
public static void main(String[] args) {
Thread downloader = new Thread(() -> {
try {
Thread.sleep(500); // simulate a slow download
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("downloader: file downloaded");
}, "downloader");
downloader.start();
System.out.println("main: opening the file now"); // too early!
}
}
Output:
main: opening the file now
downloader: file downloaded
How it works:
downloader.start()returns immediately; the download happens in the background.maingoes straight to its next line, so it "opens" the file 500 ms too early.
How to Use Java Thread join()
Adding one join() call fixes the order: main waits on that line until downloader is done.
public class WithJoin {
public static void main(String[] args) throws InterruptedException {
Thread downloader = new Thread(() -> {
try {
Thread.sleep(500); // simulate a slow download
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("downloader: file downloaded");
}, "downloader");
downloader.start();
System.out.println("main: waiting for the download...");
downloader.join(); // main pauses here until downloader has finished
System.out.println("main: opening the file now");
System.out.println("main: downloader alive? " + downloader.isAlive());
}
}
Output:
main: waiting for the download...
downloader: file downloaded
main: opening the file now
main: downloader alive? false
How it works:
downloader.join()blocksmainuntildownloader'srun()method returns.- After
join()returns,isAlive()isfalseand the thread is in theTERMINATEDstate, as described in Java Thread States.
Joining Multiple Threads in Java
To run several tasks in parallel and wait for all of them, start every thread first, then join them one by one. Joining inside the start loop would run them one after another.
import java.util.ArrayList;
import java.util.List;
public class JoinMany {
public static void main(String[] args) throws InterruptedException {
String[] reports = {"sales", "inventory", "customers"};
int[] durations = {700, 300, 500};
List<Thread> workers = new ArrayList<>();
long start = System.nanoTime();
for (int i = 0; i < reports.length; i++) {
String report = reports[i];
int millis = durations[i];
Thread worker = new Thread(() -> {
try {
Thread.sleep(millis); // simulate building the report
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(report + " report ready (" + millis + " ms)");
}, report + "-worker");
workers.add(worker);
worker.start(); // start ALL threads first...
}
for (Thread worker : workers) {
worker.join(); // ...then wait for each one
}
long totalMillis = (System.nanoTime() - start) / 1_000_000;
System.out.println("All reports ready. Took under 1000 ms: " + (totalMillis < 1000));
}
}
Output:
inventory report ready (300 ms)
customers report ready (500 ms)
sales report ready (700 ms)
All reports ready. Took under 1000 ms: true
How it works:
- All three workers start immediately and sleep at the same time, so the total time is about 700 ms (the slowest one), not 1500 ms (the sum).
- The second loop joins each thread in list order. Joining
salesfirst takes 700 ms; by then the other two have already finished, so theirjoin()calls return at once. - The order in which you join does not change the total time.
Collecting Results from Threads with join()
join() also guarantees visibility: everything a thread wrote before it ended is visible to the thread that joined it. That makes it safe to read results after join() returns.
public class JoinSum {
// Each worker stores its result in its own slot, so no locking is needed
static long[] partialSums = new long[4];
public static void main(String[] args) throws InterruptedException {
int[] numbers = new int[1_000_000];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1; // 1, 2, 3, ..., 1,000,000
}
int parts = partialSums.length;
int chunk = numbers.length / parts;
Thread[] workers = new Thread[parts];
for (int p = 0; p < parts; p++) {
int index = p;
int from = p * chunk;
int to = (p == parts - 1) ? numbers.length : from + chunk;
workers[p] = new Thread(() -> {
long sum = 0;
for (int i = from; i < to; i++) {
sum += numbers[i];
}
partialSums[index] = sum;
});
workers[p].start();
}
for (Thread worker : workers) {
worker.join(); // after join, the worker's result is safely visible
}
long total = 0;
for (int p = 0; p < parts; p++) {
System.out.println("part " + p + ": " + partialSums[p]);
total += partialSums[p];
}
System.out.println("total : " + total);
System.out.println("check : " + (1_000_000L * 1_000_001L / 2));
}
}
Output:
part 0: 31250125000
part 1: 93750125000
part 2: 156250125000
part 3: 218750125000
total : 500000500000
check : 500000500000
How it works:
- The array of one million numbers is split into four chunks, and each worker adds up its own chunk.
- Each worker writes to its own slot in
partialSums, so the threads never write to the same variable. - After all four
join()calls,mainreads the four slots safely and adds them. The total matches the formulan × (n + 1) / 2.
Note: Reading a worker's result without
join()(or another synchronization tool) is unsafe:mainmight see an old value. The rules behind this are covered in Java Synchronization.
Java Thread join() with a Timeout
join(millis) waits at most the given time. It returns void, so after it returns you check isAlive() to find out whether the thread finished or the time ran out.
public class JoinTimeout {
public static void main(String[] args) throws InterruptedException {
Thread slowBackup = new Thread(() -> {
try {
Thread.sleep(3000); // a backup that takes 3 seconds
System.out.println("backup: finished");
} catch (InterruptedException e) {
System.out.println("backup: cancelled");
}
}, "backup");
slowBackup.start();
slowBackup.join(1000); // wait at most 1 second
if (slowBackup.isAlive()) {
System.out.println("main: backup still running after 1 s, cancelling it");
slowBackup.interrupt();
slowBackup.join(); // wait for it to react to the interrupt
}
System.out.println("main: backup alive? " + slowBackup.isAlive());
}
}
Output:
main: backup still running after 1 s, cancelling it
backup: cancelled
main: backup alive? false
How it works:
slowBackup.join(1000)returns after one second, even though the backup needs three.isAlive()is stilltrue, somaininterrupts the backup. Itssleep()throwsInterruptedExceptionand the thread ends.- A final
join()without a timeout waits for the backup to finish reacting to the interrupt.
join(Duration) Returns Whether the Thread Finished
Since Java 19, join(Duration) tells you directly whether the thread terminated in time, so you do not need a separate isAlive() check.
import java.time.Duration;
public class JoinDuration {
static Thread task(String name, long millis) {
Thread t = new Thread(() -> {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, name);
t.start();
return t;
}
public static void main(String[] args) throws InterruptedException {
Thread quick = task("quick", 200);
Thread slow = task("slow", 2000);
// join(Duration) returns true if the thread terminated in time (Java 19+)
boolean quickDone = quick.join(Duration.ofMillis(500));
boolean slowDone = slow.join(Duration.ofMillis(500));
System.out.println("quick finished within 500 ms: " + quickDone);
System.out.println("slow finished within 500 ms : " + slowDone);
slow.join(); // wait for the rest before exiting
}
}
Output:
quick finished within 500 ms: true
slow finished within 500 ms : false
How it works:
quicksleeps 200 ms, so it finishes within the 500 ms limit andjoinreturnstrue.slowsleeps 2000 ms, sojoingives up after 500 ms and returnsfalse.
join() on a Thread That Was Never Started
join() waits only while the thread is alive. A thread that has not been started yet is not alive, so join() returns immediately without waiting.
public class JoinNotStarted {
public static void main(String[] args) throws InterruptedException {
Thread report = new Thread(() -> System.out.println("report: generated"), "report");
long start = System.nanoTime();
report.join(); // report was never started: join() returns at once
long waitedMicros = (System.nanoTime() - start) / 1_000;
System.out.println("main: join() returned, state = " + report.getState());
System.out.println("main: waited less than 1 ms: " + (waitedMicros < 1000));
report.start();
report.join(); // now it really waits for the thread to finish
System.out.println("main: state after real join = " + report.getState());
}
}
Output:
main: join() returned, state = NEW
main: waited less than 1 ms: true
report: generated
main: state after real join = TERMINATED
How it works:
- The first
report.join()happens whilereportis stillNEW. It returns at once and the report has not been generated. - After
report.start(), the secondjoin()really waits until the thread isTERMINATED. - Always call
start()before relying onjoin().
Interrupting a Thread That Is Waiting in join()
A thread blocked in join() is in the WAITING state. If another thread interrupts it, join() stops waiting and throws InterruptedException. The thread it was joining keeps running.
public class JoinInterrupted {
public static void main(String[] args) throws InterruptedException {
Thread endless = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
Thread.onSpinWait(); // keeps running until interrupted
}
}, "endless");
Thread waiter = new Thread(() -> {
try {
System.out.println("waiter: joining endless...");
endless.join(); // would wait forever
} catch (InterruptedException e) {
System.out.println("waiter: interrupted while joining, giving up");
}
}, "waiter");
endless.start();
waiter.start();
Thread.sleep(300);
System.out.println("main: waiter state = " + waiter.getState());
waiter.interrupt(); // stop waiting
waiter.join();
endless.interrupt(); // stop the endless thread too
endless.join();
System.out.println("main: both threads stopped");
}
}
Output:
waiter: joining endless...
main: waiter state = WAITING
waiter: interrupted while joining, giving up
main: both threads stopped
How it works:
waitercallsendless.join(), which would never return, becauseendlessloops until it is interrupted.maininterruptswaiter. Itsjoin()throwsInterruptedException, andwaitergives up.- Interrupting
waiterdoes not stopendless;mainhas to interruptendlessseparately.
Running Threads in Order with join()
Threads can join each other to build a simple chain of steps: each step waits for the one before it.
public class JoinOrder {
public static void main(String[] args) throws InterruptedException {
Thread validate = new Thread(() -> System.out.println("1. validate cart"));
Thread charge = new Thread(() -> {
try {
validate.join(); // charge only after validation is done
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println("2. charge card");
});
Thread ship = new Thread(() -> {
try {
charge.join(); // ship only after the payment is done
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println("3. ship order");
});
// Start each thread before any thread that joins it
validate.start();
charge.start();
ship.start();
ship.join();
System.out.println("order complete");
}
}
Output:
1. validate cart
2. charge card
3. ship order
order complete
How it works:
chargecallsvalidate.join()before charging, andshipcallscharge.join()before shipping.- The threads are started in dependency order, so every thread that gets joined has already been started (see the previous section for why that matters).
- The output order is always the same, even though three threads are involved.
join() | Thread.sleep() | |
|---|---|---|
| Waits for | Another thread to finish | A fixed amount of time |
| Called on | The thread to wait for (t.join()) | The class (Thread.sleep(ms)) |
| Ends early when | The thread finishes | Never (only on interrupt) |
| Use to coordinate threads | Yes | No; guessing a delay is unreliable |
For more on pausing a thread for a fixed time, see Java Thread Sleep.
Real-World Example: Load an Order Page from Several Services
An order page needs data from four backend services. Calling them one after another would be slow, so each call runs in its own thread. The page has a time budget of 800 ms: any service that has not answered by then is cancelled and replaced with a fallback text.
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
public class OrderSummaryJob {
// A worker thread that loads one piece of data and keeps the result
static class Loader extends Thread {
private final long delayMillis;
private final String value;
private String result; // written by this thread, read by main after join()
Loader(String name, long delayMillis, String value) {
super(name);
this.delayMillis = delayMillis;
this.value = value;
}
@Override
public void run() {
try {
Thread.sleep(delayMillis); // simulate a remote call
result = value;
} catch (InterruptedException e) {
result = null; // cancelled
}
}
String result() {
return result;
}
}
public static void main(String[] args) throws InterruptedException {
Map<String, Loader> loaders = new LinkedHashMap<>();
loaders.put("customer", new Loader("customer-service", 300, "Priya Nair (Gold member)"));
loaders.put("items", new Loader("cart-service", 450, "3 items, Rs. 2,450"));
loaders.put("shipping", new Loader("shipping-service", 250, "Delivery by Thursday"));
loaders.put("offers", new Loader("offers-service", 5000, "10% off next order"));
long start = System.nanoTime();
loaders.values().forEach(Thread::start); // all calls run in parallel
Duration budget = Duration.ofMillis(800); // the page must render within 800 ms
long deadline = System.nanoTime() + budget.toNanos();
Map<String, String> summary = new LinkedHashMap<>();
for (Map.Entry<String, Loader> entry : loaders.entrySet()) {
Loader loader = entry.getValue();
long remainingNanos = Math.max(0, deadline - System.nanoTime());
boolean finished = loader.join(Duration.ofNanos(remainingNanos));
if (finished) {
summary.put(entry.getKey(), loader.result());
} else {
loader.interrupt(); // too slow: cancel and use a fallback
summary.put(entry.getKey(), "(not available right now)");
}
}
long tookMillis = (System.nanoTime() - start) / 1_000_000;
System.out.println("=== Order Summary ===");
summary.forEach((section, text) -> System.out.printf("%-9s: %s%n", section, text));
System.out.println("Rendered within budget: " + (tookMillis < 900));
}
}
Output:
=== Order Summary ===
customer : Priya Nair (Gold member)
items : 3 items, Rs. 2,450
shipping : Delivery by Thursday
offers : (not available right now)
Rendered within budget: true
How it works:
- One thread per service.
LoaderextendsThread(see Java Thread Class) and stores its result in a field. All four loaders start together. - One shared deadline. Instead of giving each
join()a fresh 800 ms, the code computes a singledeadlineand passes only the remaining time to eachjoin(Duration). The whole page therefore waits at most 800 ms in total. - Using the boolean result.
join(Duration)returnstruefor the three fast services, so their results are read safely after the join. - Fallback for slow services. The offers service needs 5 seconds. Its
joinreturnsfalse, so the loader is interrupted and the page shows a placeholder instead of making the customer wait. - Fast overall. The page is ready after about 800 ms, even though one service would have taken 5 seconds.