Victor Grazi
Victor Grazi

Reputation: 16490

Thread dump showing incorrect thread state

I am trying to diagnose a production issue. I set up a little test program on Mac OS Lion that launches 10 threads (using Executors.newCachedThreadPool() which all call MUTEX.wait(), in a synchronized block)

Then I do a kill -3 to get a thread dump, and I see all of my threads showing BLOCKED. Shouldn't these all be WAITING?

The code is something like this, (forgive the code smells introduced for brevity)

ExecutorService executor = Executors.newCachedThreadPool();
final Object MUTEX = new Object();
for(int i = 0; i < 10; i++) {
   executor.execute(new Runnable() {
      public void run() {
        synchronized(MUTEX) {
         MUTEX.wait();
}  }   }}

At this point all threads should be in the WAITING state but in fact a thread dump shows all are BLOCKED

Upvotes: 1

Views: 270

Answers (1)

reprogrammer
reprogrammer

Reputation: 14718

Because your threads are waiting for a monitor lock to enter a synchronized block/method, their status is BLOCKED.

A thread that is blocked waiting for a monitor lock is in the BLOCKED state and a thread that is waiting indefinitely for another thread to perform a particular action is in the WAITING state.

See below for more details about the difference between BLOCKED and WAITING:

From the JavaDoc of BLOCKED:

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

From the JavaDoc of WAITING:

A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.

Upvotes: 4

Related Questions