Sunday, September 28, 2008

Java NIO [reading note]

- NIO is primarily block oriented, uses streams
page-oriented nature of system I/O (disk, file)
stream I/O, OS provides non-blocking, readiness selection support

- Channels are conduits to OS I/O service, not stream. They do bulk data transfer to and from buffer, channel.write(buffer) ~= buffer.get(byteArray), buffer.put(byteArray). Data is logically transferred in blocks, not char/byte at a time.

- Channels are gateways through which the native I/O services of the operating system can be accessed with a minimum of overhead, and buffers are the internal endpoints used by channels to send and receive data. Channel implementations often use native code. The channel interfaces allow you to gain access to low-level I/O services in a controlled and portable way.

- The new socket channels can operate in nonblocking mode and are selectable. These two capabilities enable multiplexed I/O.

- Readiness selection effectively prevents you from separating the code that checks for readiness from the code that processes the data, at least without significant complexity.

- A SelectionKey encapsulates the registration relationship between a specific channel and a specific selector. SelectionKey objects contain two bit sets (encoded as integers) interest set and ready set indicating which channel operations the registrant has an interest in and which operations the channel is ready to perform.

- Building Highly Scalable Servers with Java NIO has a good discussion on thread model:

  • M dispatchers/no workers
Several event-dispatch threads doing all the work (dispatching events, reading, processing requests, and writing).
  • 1 dispatcher/N workers
A single event-dispatch thread and multiple worker threads.
  • M dispatchers/N workers
Multiple event dispatch threads and multiple worker threads.

- More thread != More efficient. More thread means more context switching overhead. Actual concurrency is limited by the number of CPUs available.

See: Introducing Nonblocking Sockets

No comments: