Java NiO Tutorial (i) Core Overview
Java NIO consists of the following core components: Channels buffers Selectors
Although there are many other classes and components in Java NIO, it seems to me that Channel,buffer and Selector constitute the core API. Other components, such as pipe and filelock, are just tool classes that are used in conjunction with three core components. Therefore, I will focus on these three components in the overview. Other components are described in a separate section.
Channel and Buffer
Basically, all IO starts with a channel in NiO. Channel a bit like a stream. Data can be read from channel to buffer or written to channel from buffer. Here's a diagram:
There are several types of channel and buffer. The following are the implementations of some of the major channel in Java NIO: FileChannel datagramchannel socketchannel Serversocketchannel
As you can see, these channels cover both UDP and TCP network IO, as well as file IO.
There are some interesting interfaces with these classes, but for the sake of simplicity, I try not to mention them in the overview. I will explain the other chapters of this tutorial that relate to them.
The following are key buffer implementations in Java NIO: Bytebuffer charbuffer doublebuffer floatbuffer intbuffer longbuffer
These buffer covers the basic data types you can send via IO: Byte, short, int, long, float, double, and Char.
Java NIO also has a mappedbytebuffer that represents the memory-mapped file, and I do not intend to explain it in the overview. Selector
Selector allows multiple Channel to be processed in a single thread. If your application opens multiple connections (channels), but the traffic is low for each connection, it is convenient to use selector. For example, in a chat server.
This is a single thread that uses a selector to handle 3 channel diagrams:
To use selector, you have to register the channel with selector, and then call its select () method. This method blocks to a registered channel until the event is ready. Once this method returns, the thread can handle these events, with examples of events like new connections coming in, data receiving, and so on.