Java NIO consist of the following core components:

  • Channels
  • Buffers
  • Selectors Java NIO has more classes and components than these, but channels, buffers, and Selectors are, in my opinion, the heart of the API. The rest of the components, such as Pipe and FileLock, are just utility classes to be used with the three core components. Therefore, I will focus on these three components in this NIO overview. In general, all IO in NIO starts with a channel. A channel is a bit like a stream. Channel data can be read into a buffer. Data can also be written from buffers to channels. Here’s an example:

    There are several channel and buffer types. The following is a list of the main implementations of channels in Java NIO:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel As you can see, these channels cover UDP + TCP network IO and file IO.

Here is a list of core buffer implementations in Java NIO:

  • ByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • These buffers cover the basic types of data that you can send via IO: Byte, short, int, long, float, double and characters. ###Selectors allow a single thread to handle multiple channels. This is handy if your application has multiple connections (channels) open, but only low traffic per connection. For example, in a chat server.

Here is an example of a thread handling three channels using Selector: