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

TIMED_WAITING State: Waiting with Timeout

How sleep(), wait(timeout), join(timeout) put threads in TIMED_WAITING and automatic awakening after timeout.

TIMED_WAITING State: Waiting with Timeout

You'll learn how Java threads automatically wake up after a specified timeout using methods like sleep(), wait(timeout), and join(timeout).

What Is TIMED_WAITING?

While the WAITING state parks a thread indefinitely until another thread wakes it, TIMED_WAITING is like setting an alarm clock. The thread waits for a condition or a maximum time limit—whichever comes first. After the timeout expires, the JVM automatically moves the thread back to RUNNABLE, ready to compete for CPU time.

Methods That Trigger TIMED_WAITING

Three common methods put threads into this state:

Thread.sleep(milliseconds)

Pauses the current thread for a specified duration. The thread relinquishes CPU but holds onto any locks it owns.

Thread.sleep(5000); // TIMED_WAITING for 5 seconds
// Automatically returns to RUNNABLE when time expires

wait(timeout)

Similar to wait(), but with a time limit. If no thread calls notify() before the timeout, the thread automatically wakes up.

synchronized(obj) {
    obj.wait(3000); // TIMED_WAITING for up to 3 seconds
}

join(timeout)

Waits for another thread to complete, but only for a specified duration.

otherThread.join(2000); // Wait max 2 seconds for otherThread

Automatic Awakening

The key difference from WAITING: you don't need another thread to wake you up. The JVM scheduler automatically transitions the thread back to RUNNABLE after the timeout, even if the condition you were waiting for never occurred. Your code must check whether the wait succeeded or timed out.

Key Takeaway: TIMED_WAITING lets threads wait with a safety net—they'll wake automatically after the specified timeout, preventing indefinite blocking.