NIO

July 28th, 2008 by michael

Quite some time ago Sun decided that Java needed a new IO architecture, and so NIO was born. You can use Java and be safely ignorant of NIO for most purposes, until you come to high performance servers, fast copy operations, etc…  Anywhere where speed is of the essence.

NIO supports concepts such as non-blocking IO, selectors and memory mapped files. There are other ideas in there, but I feel that these are the main ones.

Recently I had a play, just to keep my skills in check, and wrote a small file server. It’s multithreaded, and uses selectors to manage multiple IO requests per thread. It’s simple, really simple, and that’s what might make it a good reference for you.

First is the ConnectionListener. This listens on a ServerSocketChannel for connections, and farms them out to request threads. It has a backlog of 8 in this example, but that can be extended. If a new connection arrives whilst it is processing the old one, that’s ok as the OS will hold it in a queue.

Second is the RequestListener. This listens to multiple non-blocking SocketChannel’s farming IO requests out to other classes. Here is the key, a single thread handles multiple sockets, but there are also multiple threads. Whilst we don’t want to bog down the system with threads, we do want to take advantage of multiple CPU’s and file IO latency to gain performance. A simple round robin approach is used to spread requests across the threads.

Lastly there is Request itself. This class abstracts the process of handling a file request from the listener thread. It uses a FileChannel with a MappedByteBuffer to read the file contents.

Here are the source files:

If you find this useful, please link to this post.

Share/Save/Bookmark

Leave a Reply