Problem reading from nio socketchannels into a bytebuffer

J

Jeff Silvis

At:
http://www.javanio.info/filearea/bo...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
 
P

Paul Lutus

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)?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top