Java NIO (I) Java NIO overview, javanio Overview
Java NIO consists of the following core components:
- Channels
- Buffers
- Selectors
Although there are many classes and components in Java NIO, in my opinion, Channel, Buffer and Selector constitute the core API. Other components, such as Pipe and FileLock, are only tool classes used together with the three core components. Therefore, in the overview, I will focus on these three components. Other components are described in separate sections.
Channel and Buffer
Basically, all IO operations start from a Channel in NIO. The Channel is a bit like a stream. Data can be read from the Channel to the Buffer, or written from the Buffer to the Channel. Here is an illustration:
There are several types of channels and Buffer. Below are some major Channel implementations in java nio:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
As you can see, these channels cover UDP and TCP network IO, and file IO.
There are some interesting interfaces with these classes, but for simplicity, I try not to mention them in the overview. I will explain other topics related to them in this tutorial.
The following are the key Buffer implementations in Java NIO:
- ByteBuffer
- CharBuffer
- DoubleBuffer
- FloatBuffer
- IntBuffer
- LongBuffer
- Protocol Buffer
These buffers cover the basic data types that can be sent through IO: byte, short, int, long, float, double, and char.
Java NIO also has a MappedByteBuffer, which is used to indicate memory ing files. I am not going to explain it in the overview.
Selector
Selector allows a single thread to process multiple channels. If your application opens multiple connections (channels), but the traffic for each connection is low, it is very convenient to use Selector. For example, in a chat server.
This is an illustration that uses a Selector to process three channels in a single thread:
To use Selector, you must register a Channel with Selector and call its select () method. This method will be blocked until a registered channel has an event ready. Once this method is returned, the thread can process these events, such as new connections and data reception.