Original address: http://ifeve.com/overview/
Statement: The Java NIO series of textbooks is not my original, only because after reading the original feeling in the article of the exquisite, intended to share with you, therefore, this is the worst, forget the original author forgive me. Also attached is the original address.
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 form 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. The Channel is a bit like a stream. Data can be read from the channel to buffer, or it can be written from buffer to the channel. Here's a diagram:
There are several types of channel and buffer. Here are some of the main channel implementations 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 along 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 where they relate.
The following are the key buffer implementations in Java NIO:
- Bytebuffer
- Charbuffer
- DoubleBuffer
- Floatbuffer
- Intbuffer
- Longbuffer
- Shortbuffer
These buffer covers the basic data types that you can send via IO: Byte, short, int, long, float, double, and Char.
Java NIO also has a mappedyteuffer, which is used to represent memory-mapped files, and I do not intend to describe them in the overview.
Selector
Selector allows single-threaded processing of multiple Channel. If your app has multiple connections (channels) open, but the traffic is low for each connection, it's convenient to use selector. For example, in a chat server.
This is the illustration of using a selector to process 3 channel in a single thread:
To use selector, you have to register the channel with selector and then call its select () method. This method will always block to a registered channel with event readiness. Once this method returns, the thread can handle these events, with examples of events such as new connections coming in, data receiving, and so on.
Java NIO Series tutorial (i) Java NiO overview