Re: big cpu consumption
On Mon, 18 Aug 2008, EJP wrote:
That's what we call a busy-wait
No it's not.
Well, actually it is, although it's waiting for a condition which will
never occur.
, and it is indeed a very good way to waste all your CPU time.
There is no CPU time being used here at all actually. There is
wall-clock time being spent while the read() method blocks. Not the same
thing.
And also not what the OP reported:
"I have a big problem with cpu usage. when i listen microphone to record
what comes, cpu time is consumed apr. 80% everytime which seems
unnecessary."
Clearly, CPU time *is* being used, and this *is* a busy-wait. But, having
read what you read elsewhere in this thread, i realise my diagnosis (based
not on knowledge of the API, but on inference from what the OP wrote, ie
guesswork - my bad!) was misguided. I thought that read() was returning -1
when there wasn't data available, which is not what the documentation
says. I imagine your suggestion of sorting out start() is the right one.
while ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
try {
Thread.sleep(t) ;
}
catch (InterruptedException e) {
// can probably ignore this
}
}
Where t is a duration in milliseconds. This basically means that your
program will wait for a while before trying to read data again. It
won't be consuming CPU while it waits.
Excuse me but this is all nonsense. The read() will return -1 at the end
of the stream. At this point there will *never* be any more data on the
stream.
Fair enough. If the OP's program is busy-waiting for data which will never
come, my approach will still reduce CPU use, though - it makes the
pointless wait far more efficient!
tom
--
Suddenly, everything is clear ...