java sleep 释放cpu不,使用Thread.sleep时线程处于睡眠状态时的CPU消耗

I have a server program which polls a database for new requests , I want this polling to be done at 1 minute intervals so , I've set up a Thread.sleep() in the program while loop.

The problem is that whenever this program is supposed to "sleep" the CPU consumption goes up drastically (viz. about 25 - 30%).

Paradoxically, when the program is not dormant and is busy processing requests , the CPU consumption drops to 0.4%.

I read online and found out that there are performance hits associated with thread.sleep, but I could not find any viable alternative (Thread.wait requires notification on an object, something which I feel is useless in my scenario)

The main loop (when there are no new requests) doesn't do anything, here is a skeleton of all that is being done when the CPU consumption is 25%

-> poll

-> No new records ?

-> Sleep

->repeat

解决方案

Check what the CPU consumption is for individual CPU cores. If you are using a 4 core machine, maybe one thread is going rogue and is eating up once core (25%). This usually happens when the thread is in a tight loop.

You could use Thread.wait with a timeout (which indeed the Timer class does), but my bet is that it won't make any difference. Both Thread.sleep and Thread.wait changes the threads' state to not runnable. Although it depends on your JVM implementation etc., the thread shouldn't consume that much CPU in such situation. So my bet is that there is some bug at work.

Another thing you can do is taking a thread dump and see what the thread is doing when this happens. Use kill -3 on a Linux box, or use ctrl+break on the java console window if you are using Windows. Then, examine the thread dump that is dumped to the standard output. Then you can be sure if the thread was actually sleeping or was doing something else.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值