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

Thread.getState() and Monitoring Thread States

Using Thread.State enum and getState() method to inspect thread state at runtime for debugging and monitoring.

Thread.getState() and Monitoring Thread States

What You'll Learn

You'll learn how to programmatically inspect a thread's current state at runtime using the Thread.State enum and getState() method—essential for debugging concurrent applications.

The Inspection Tool You Need

Think of Thread.getState() as a diagnostic tool that lets you peek at what a thread is currently doing, much like checking a package's tracking status. While threads transition between states automatically, being able to query their state gives you visibility into your application's concurrency behavior.

The Thread.State Enum

Java provides the Thread.State enum with these five values:

  • NEW – Created but not started
  • RUNNABLE – Executing or ready to execute
  • BLOCKED – Waiting for a monitor lock
  • WAITING – Waiting indefinitely
  • TIMED_WAITING – Waiting with a timeout
  • TERMINATED – Finished execution

Using getState()

The getState() method returns the current state of any thread:

Thread worker = new Thread(() -> {
    // Some task
});

Thread.State state = worker.getState();
System.out.println("State: " + state); // NEW

worker.start();
state = worker.getState();
System.out.println("State: " + state); // RUNNABLE

Monitoring Example

You can poll thread states for debugging:

Thread task = new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {}
});

task.start();
Thread.State current = task.getState();
System.out.println("Initial: " + current); // RUNNABLE or TIMED_WAITING

Important Limitations

The state you retrieve is a snapshot—the thread may have already transitioned to a different state by the time you read the value. Don't use getState() for synchronization or control flow; it's primarily a debugging and monitoring tool.

Key Takeaway: Thread.getState() returns a Thread.State enum value representing the thread's current state snapshot, invaluable for debugging but unreliable for synchronization due to race conditions.