Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Problem reading from nio socketchannels into a bytebuffer

Reply
Thread Tools

Problem reading from nio socketchannels into a bytebuffer

 
 
Jeff Silvis
Guest
Posts: n/a
 
      09-16-2004
At:
http://www.javanio.info/filearea/boo...ctSockets.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
 
Reply With Quote
 
 
 
 
Paul Lutus
Guest
Posts: n/a
 
      09-16-2004
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
SocketChannels NIO Andersen Java 3 01-23-2006 05:28 PM
What Happens When Native Memory Space Pointed By java.nio.ByteBuffer Is Deleted res7cxbi@verizon.net Java 5 01-02-2006 09:32 PM
Get Array From ByteBuffer (If ByteBuffer doesn't have an array backing it) res7cxbi@verizon.net Java 2 01-01-2006 08:58 PM
nio ByteBuffer filling Remon van Vliet Java 3 05-19-2005 07:26 PM
[nio] Mutliple Messages in ByteBuffer Michael B Allen Java 1 12-13-2004 06:30 AM



Advertisments