java多线程应用程序:获取线程阻塞时间
我在工作线程终止之前调用 threadInfo.getBlockedCount()
和 getBlockedTime()
。 我得到的阻塞计数为 1,但阻塞时间为 0。 这是否意味着线程被阻塞,但阻塞时间小于一毫秒?
如果上述情况成立,是否有其他方法可以获取线程被阻塞的准确时间?
I am calling threadInfo.getBlockedCount()
and getBlockedTime()
just before the worker threads die.
I get a blocked count of 1, but a blocked time of 0.
Does this mean that the thread was blocked but it the blocked time was less than a millisecond?
If the above is true, is there another way to get accurate time for which a thread was blocked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但是,如果在启动线程之前调用 ThreadMXBean#setThreadContentionMonitoringEnabled(true),则线程的阻塞时间(被阻塞)似乎只会返回非零结果。否则,它总是返回零(如果禁用争用监视,则返回 -1)。下面的代码演示了这一点:
示例输出:
However, the blocked time of a thread (being blocked) only seems to return a non-zero result if the ThreadMXBean#setThreadContentionMonitoringEnabled(true) is called * before * starting the thread. Otherwise, it'd always return zero (or -1 if the contention monitoring is disabled). The code below demos this:
Sample Output:
可以测试一下,例如:
示例输出:
Can test it out, with something like:
Sample Output:
是的,这确实意味着它被阻止了 0 毫秒。即不涉及阻塞。线程没有等待监视器锁进入同步块/方法。
您看到这一点是因为您必须编写一个具有一两个线程的简单程序,并且没有延迟。
您将需要在线程上引入非常重的负载才能真正看到正值。
Yes it does mean that it was blocked for 0 milliseconds. i.e there was no blocking involved. The thread did not wait for the monitor lock to enter the synchronized block/method.
You are seeing this because you must have written a simple program with one or two threads, and there is no latency.
You will need to induce really heavy load on the threads to actually see positive values.
显然,这就是它的意思,而且显然没有办法让时间更精确。 (javadocs 说,阻塞时间可能是测量的,并且(大概)以更高的精度累积,但是 ThreadInfo API 没有公开此信息,并且似乎没有任何其他更合理的方式)
我说“显然”,因为 javadoc 实际上将时间值描述为“近似累计经过时间”。这使得这可能是一个非常粗略的近似值,可能与 System.getCurrentTimeMillis() 返回的时钟值具有相同的粒度。此外,它没有说明用高精度计时器测量的累积时间在转换为毫秒值时是否会四舍五入或截断;即零是否表示“小于 1 毫秒”或“小于 0.5 毫秒”。
Apparently, that is what it means, and apparently there isn't a way to get the time to a greater precision. (The javadocs say that the blocked time may be measured and (presumably) accumulated with greater precision, but the ThreadInfo API doesn't expose this information, and there doesn't appear to be any other kosher way to get it.)
I say "apparently", because the javadoc actually describes the time values as "the approximate accumulated elapsed time". This leaves open the possibility that this could be a very rough approximation, possibly with the same granularity as the clock values returned by
System.getCurrentTimeMillis()
. Also, it doesn't say if accumulated times measured with a high precision timer would be rounded or truncated when converted to millisecond values; i.e. whether zero means "less than 1 millisecond" or "less than 0.5 milliseconds".