Problem reading from nio socketchannels into a bytebuffer  
Author Message
silvis





PostPosted: 2004-9-16 23:06:00 Top

java-programmer, Problem reading from nio socketchannels into a bytebuffer At:
http://www.javanio.info/filearea/bookexamples/unpacked/com/ronsoft/books/nio/channels/SelectSockets.java

There is sample code. In that page there are the lines:




// send the data, don't assume it goes all at once
while (buffer.hasRemaining()) {
socketChannel.write (buffer);
}
// WARNING: the above loop is evil. Because
// it's writing back to the same non-blocking
// channel it read the data from, this code can
// potentially spin in a busy loop. In real life
// you'd do something more useful than this.




In some of my code I have written a line more or less exactly like:
while (buffer.hasRemaining()) {
socketChannel.write (buffer);
}


and the code does just spin. What is an example of "something more
useful than this"?

Jeff
 
Paul Lutus





PostPosted: 2004-9-16 23:49:00 Top

java-programmer >> Problem reading from nio socketchannels into a bytebuffer Jeff Silvis wrote:

/ ...

[ about non-blocking I/O methods ]

> In some of my code I have written a line more or less exactly like:
> while (buffer.hasRemaining()) {
> socketChannel.write (buffer);
> }
>
>
> and the code does just spin. What is an example of "something more
> useful than this"?

Obviously if you plan to use this kind of code, put it in a separate thread
and use the blocking version of these I/O classes. What you in essence have
done is use a non-blocking method and have arranged to block with it, in a
particularly wasteful way.

To put it another way, you never want to loop on a non-blocking method,
because the method won't block for you. Your code is written to accommodate
a conventional blocking I/O call.

So please answer this question. Did you really want a blocking method and
chose this one by mistake, or did you really want to learn how to use
non-blocking methods, and chose this loop structure by mistake (even if
from an "official " Web site)?

--
Paul Lutus
http://www.arachnoid.com