Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best model for an NIO implementation?

Tags:

java

nio

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?

like image 879
Stephen Avatar asked Sep 21 '09 15:09

Stephen


2 Answers

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?

like image 175
pjp Avatar answered Sep 20 '22 00:09

pjp


You really should look into Mina,

http://mina.apache.org/

It solves all the problems you mentioned.

like image 44
ZZ Coder Avatar answered Sep 18 '22 00:09

ZZ Coder