The goal of this example
Most software developers are comfortable with threading and the good old blocking I/O operations. While the java IO support is pretty easy to use, the drawback is that you need a thread for each stream to read/write. Threading is easy, but it has a small price. Part of this price is the kernel overhead the threads generate, this is relatively insignificant and may not be the most limiting factor. The other and probably more significant part of the price is the memory one thread takes.How can we work it around? That is what NIO (non-blocking/new IO) is for. You do not start a thread for each client.
Let me show you an example. I have an old Raspberry PI B model with only 256 MB memory. I wanted to know if I can use this raspberry PI to fetch performance statistics from 512 hosts at the same time. The idea was that I will just ssh there and open a command channel with ‘vmstat 1’ and parse the output, simple enough.
Let’s calculate with blocking IO: you need 512 threads for your 512 clients, each will take half a MB from the heap for the stack and a little more to keep its data. That is already more than 256 MB of heap memory, while I only have 100something free. Blocking IO is no-go with blocking IO on this small hardware.
Ok, then let’s give it a try with NIO!
- Apache Mina
- Apache SSHD – client part only