Java阻塞线程是否会占用更多CPU资源?
我想问当线程被阻塞时,即等待锁定当前被另一个线程锁定的监视器时,Java是否会利用更多的CPU资源。
我现在正在查看一个线程转储,其中一些线程在等待锁定监视器时被阻塞,并且我不确定这是否是造成高 CPU 使用率的原因。
谢谢!
编辑(2011 年 5 月 6 日)我忘记提及此行为是否与 Java SE 1.4.2 相关。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
线程消耗内存等资源。阻塞/解除阻塞线程会产生一次性成本。如果线程每秒阻塞/解除阻塞数万次,则可能会浪费大量 CPU。
然而,一旦线程被阻塞,无论阻塞多长时间,都不会产生持续的成本。
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.
答案并不那么简单。在某些情况下,进入阻塞状态的线程最终可能会导致 CPU 利用率过高。
大多数 JVM 采用分层锁定算法。通常涉及诸如自旋锁之类的算法,特别是对于短期持有的锁。当线程尝试获取监视器但发现无法获取监视器时,JVM 实际上可能会将其放入循环中并让线程尝试获取监视器,而不是立即将其切换到上下文。如果线程在一定次数的尝试或持续时间后未能获取锁(取决于特定的 JVM 实现),JVM 会切换到“胖锁”或“膨胀锁”模式,在该模式下上下文会切换出该线程。
由于自旋锁行为,您可能会产生 CPU 成本。如果您的代码保持锁定的时间很短并且争用程度很高,那么您可能会看到 CPU 利用率出现明显的上升。有关 JVM 用于降低争用成本的各种技术的讨论,请参阅 http://www.ibm.com/developerworks/java/library/j-jtp10185/index.html。
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.
不会,监视器上阻塞的线程不会占用额外的 CPU 时间。
No, threads that are blocked on a monitor do not take up additional CPU time.
挂起或阻塞的线程不消耗任何CPU时间。
Suspended or blocked thread do not consume any CPU time.