H
Harald Kirsch
For a piece of code intented to be rather
generic, I thought it would be a good idea
that it reads its input from a
ReadableByteChannel. The main reason to
choose it over an InputStream was that the
channel can be obtained for an InputStream as
well as for a RandomAccessFile.
Now the question:
How do you correctly perform a blocking read
from a ReadableByteChannel given that it does
not necessarily block?
I came up with
ReadableByteChannel source;
ByteBuffer inBuf;
...
int result;
while( 0==(result=source.read(inBuf)) ) Thread.yield();
In case the channel is blocking, the yield()
will never be called. If the channel is
non-blocking, the yield() may be called. But
on a machine without much load, I am afraid
it will generate load because no other thread
is interested in the processor.
Any ideas how this can be done better?
Harald.
generic, I thought it would be a good idea
that it reads its input from a
ReadableByteChannel. The main reason to
choose it over an InputStream was that the
channel can be obtained for an InputStream as
well as for a RandomAccessFile.
Now the question:
How do you correctly perform a blocking read
from a ReadableByteChannel given that it does
not necessarily block?
I came up with
ReadableByteChannel source;
ByteBuffer inBuf;
...
int result;
while( 0==(result=source.read(inBuf)) ) Thread.yield();
In case the channel is blocking, the yield()
will never be called. If the channel is
non-blocking, the yield() may be called. But
on a machine without much load, I am afraid
it will generate load because no other thread
is interested in the processor.
Any ideas how this can be done better?
Harald.