S
stevengarcia
I've got a question about busy waiting. Our application controls
hardware devices via the serial port, so we are constantly writing
commands to the devices via an OutputStream, and reading the responses
from an InputStream.
I'm looking at a block of code in my codebase and it's doing the
following:
public String read(InputStream in) throws IOException {
while (in.available() <= 0) {
try {
Thread.sleep(10);
} catch(InterruptedException e) {
log.warn("Thread was interupted while sleeping", e);
}
}
...
// read from input stream...
}
The reason why the code is waiting is that the InputStream that we get
from the underlying serial port library (javax.comm) doesn't implement
InputStream properly, and it's recommended that we call in.available()
until there is actually some data available to read.
To prevent a busy wait that consumes the entire CPU, the code sleeps
for 10 ms (a very short period of time.) I've watched the CPU and it
doesn't appear pegged when this code runs.
My question is whether you think this is an effective way of avoiding
the "busy wait" problem by only sleeping for just 10ms? I would think
that the CPU would still go crazy if it only had to sleep for 10 ms.
Any opinions on this?
hardware devices via the serial port, so we are constantly writing
commands to the devices via an OutputStream, and reading the responses
from an InputStream.
I'm looking at a block of code in my codebase and it's doing the
following:
public String read(InputStream in) throws IOException {
while (in.available() <= 0) {
try {
Thread.sleep(10);
} catch(InterruptedException e) {
log.warn("Thread was interupted while sleeping", e);
}
}
...
// read from input stream...
}
The reason why the code is waiting is that the InputStream that we get
from the underlying serial port library (javax.comm) doesn't implement
InputStream properly, and it's recommended that we call in.available()
until there is actually some data available to read.
To prevent a busy wait that consumes the entire CPU, the code sleeps
for 10 ms (a very short period of time.) I've watched the CPU and it
doesn't appear pegged when this code runs.
My question is whether you think this is an effective way of avoiding
the "busy wait" problem by only sleeping for just 10ms? I would think
that the CPU would still go crazy if it only had to sleep for 10 ms.
Any opinions on this?