Course contentsShow
← Java
Lesson 2613 of 2,87048. Concurrency FundamentalsFree lesson

Checking Thread State After join Returns

Determine if a thread actually finished or if join timed out by checking isAlive.

Checking Thread State After join Returns

What you'll learn: How to determine whether a thread truly finished or if your join() call simply timed out.

When you use join() with a timeout (like thread.join(1000)), the method returns in one of two scenarios: either the thread completed its work, or the timeout expired while the thread was still running. The method signature doesn't tell you which happened—it just returns void either way.

The Problem

Imagine waiting outside a restaurant for a friend. You agree to wait 30 minutes. When 30 minutes pass, you stop waiting—but did your friend actually arrive during that time, or are they still on their way? You need to look around to find out.

The Solution: isAlive()

After join() returns, call isAlive() on the thread to check its state:

  • isAlive() returns false: The thread finished execution (reached TERMINATED state)
  • isAlive() returns true: The thread is still running; the timeout expired

Practical Example

Thread worker = new Thread(() -> {
    try {
        Thread.sleep(2000);
        System.out.println("Work complete!");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
});

worker.start();
worker.join(1000); // Wait max 1 second

if (worker.isAlive()) {
    System.out.println("Timeout expired, thread still running");
    worker.interrupt(); // Optional: signal thread to stop
} else {
    System.out.println("Thread finished within timeout");
}

This pattern is essential for timeout-based coordination where you need different behavior based on whether the thread completed successfully or exceeded your patience threshold.

Key Takeaway: Always check isAlive() after a timed join() returns to distinguish between successful completion and timeout expiration.