Question

i would like to ask if Java will utilize more CPU resources when threads are blocked, i.e. waiting to lock a monitor which is currently being locked by another thread.

I am now looking at a thread dump whereby some threads are blocked as they are waiting to lock a monitor, and i am unsure if that is what may be accountable for the high CPU usage.

Thanks!

EDIT (6 May 2011) I forgot to mention if this behavior is relevant for Java SE 1.4.2.

Was it helpful?

Solution

Threads consume resources such as memory. A blocking/unblocking thread incurs a once off cost. If a thread blocking/unblocks tens of thousands of times per second this can waste significant amounts of CPU.

However once a thread is blocked, it doesn't matter how long it is blocked for, there is no ongoing cost.

OTHER TIPS

The answer is not so simple. There may be cases where threads that go into the blocked state may end up causing CPU utilization.

Most JVMs employ tiered locking algorithms. The often involve algorithms such as spinlocks especially for locks held for a short duration. When a thread tries to acquire a monitor and finds it cannot, the JVM may actually put it in a loop and have the thread attempt to acquire the monitor, rather than context switching it out immediately. If the thread fails to acquire the lock after a certain number of tries or duration (depending on the specific JVM implementation), the JVM switches to a "fat lock" or "inflated lock" mode where it does context switch out the thread.

It is with the spinlock behavior where you may incur CPU costs. If you have code that holds lock for a very short duration and the contention is high, then you may see appreciable bump in the CPU utilization. For some discussions on various techniques JVMs use to reduce costs on contention, see http://www.ibm.com/developerworks/java/library/j-jtp10185/index.html.

No, threads that are blocked on a monitor do not take up additional CPU time.

Suspended or blocked thread do not consume any CPU time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top