NIO vs Threads

F

farseer

In this article:
http://www.onjava.com/pub/a/onjava/2002/10/02/javanio.html?page=4

the author raves about Multiplex I/O. i buy his argument regarding the
resource strain of threads vs Multiplex I/O.
but i don't see the advantage in terms of excution. in the code sample
below, it appears to be that in the while loop, if you needed to
process data recieved, the rest of the code will still be blocking on
the processing code if you were to include it in a while look.
Therefore, if you are recieving data from numerous connections and very
fast, you would want to spawn threads that actually processes the data
anyway, so that 1) you can continue reading data, 2) multiple threads
can process data as you recieve them and 3) this processing of data can
happen simultaneously across threads.
SECOND, the code below can only accept and read one input at a time.
where as if you were to use multiple threads accepting socket
connections, you could accept inputs simultaneously, no?
THIRD, with current standard Sockets, does it really block for on read?
it waits on accept(), and once a requested connection comes in, it
accepts and reads and continues. from my experience, the read has been
extremely fast. pretty much the same as below, no?
Where am i wrong?

ServerSocketChannel serverChannel = ServerSocketChannel.open();
Selector selector = Selector.open();

serverChannel.socket().bind (new InetSocketAddress (port));
serverChannel.configureBlocking (false);
serverChannel.register (selector, SelectionKey.OP_ACCEPT);

while (true) {
selector.select();

Iterator it = selector.selectedKeys().iterator();

while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();

if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel)
key.channel();
SocketChannel channel = server.accept();

channel.configureBlocking (false);
channel.register (selector, SelectionKey.OP_READ);
}

if (key.isReadable()) {
readDataFromSocket (key);
}

it.remove();
}
}

thanks
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top