Thursday, October 9, 2008

NIO server framework



- It follows one dispatcher, multiple worker threads model. The HandlerAdapter (worker thread) need to disable the channel's interest ops before the processing, to avoid selector fire more events and spawn other worker thread; it resumes channel's interest ops after the processing. However, selector is not thread-safe. So the approach is to only allow dispatcher thread updates channel's interest ops. Worker threads only queue the status change requests to dispatcher thread.

- HandlerAdapter present a Facade through which the InputHandler may interact with the framework. It encapsulates event state, channels, input and output queues. Client code registers an InputHandler for a channel, dispatcher wraps handler in an internal adapter class. The client InputHandler is decoupled from NIO and dispatcher implementation details. **Good practice **

- Client handler is passed a ChannelFacade interface through which it may interact with the channel and/or queues. **Elegant encapsulation, hide channel **

- When client code want to write data, i.e., send request, it acquires the handler, and then output byte data to the outputQueue of the channelFacade, modifies the interest ops to OP_WRITE, then next time selector will fire writable event and drain out the output queue to channel.

See: NIO Server Framework