tags:

views:

224

answers:

3

I'm in the process of converting our java code to use NIO, but I'm not sure of the best way to design it.

My initial approach was to create a pool of selector threads. The threads are started/killed as needed, and channels are registered to a selector thread when they are connected/accepted in a round-robin fashion. From there, each thread blocks on select(), and when woken up will run the appropriate callback associated with each channel that has a selected key.

In addition to this "multiple selector thread" design, I've also seen people say to use a single selector thread, and a pool of dispatch threads. When an IO operation is ready to be performed, the selector notifies a dispatcher thread, which then processes the request. This model has the benefit of not blocking the IO thread, but now we're forcing all of the IO into a single thread and dealing with synchronization/an event queue in the dispatcher.

Additionally I wouldn't be able to use a single direct byte buffer for reading each channel, passing it directly into the callback. Instead I'd have to copy the data out each time a read occurs into an array and reset. (I think..)

What's the best way to implement this?

+1  A: 

You really should look into Mina,

http://mina.apache.org/

It solves all the problems you mentioned.

ZZ Coder
Yes although it is a good idea to try and understand what is going on under the covers.
pjp
That's exactly what I did. I didn't really use Mina in my project but I learned a lot from reading their implementation.
ZZ Coder
+1  A: 

Take a look at the Reactor Pattern

http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf

How you want your selectors to work really depends on your usecase. (Number of connections, message size, etc)

What is the problem that you are trying to solve by converting from IO to NIO?

pjp
Performance and scalability. A lot fewer threads, and it should simplify our design.
Stephen Pape
+1  A: 

I found the ROX Java NIO Tutorial useful for getting started with NIO.

Grizzly is another NIO framwork (similar to MINA).

Mark