Java NiO mainly consists of the following core components:
- Channel
- Cache
- Selector Selector
Java NiO actually has more classes and components than the above, but in my opinion, Channel,buffer,selector is the core API. Other components, like pipelines and file locks, are simply generic tool classes that are used in conjunction with the three core components.
Channels and caches
In general, all IO in NiO starts with a channel. The channel is like a stream, the data can be read from the channel into a cache, the same, the data can be written into the channel from the cache
The above represents the read operation, the following represents the write operation
In Java NIO, there are several main channels:
· FileChannel
· Datagramchannel
· Socketchannel
· Serversocketchannel
These channels cover the IO and file IO of the TCP,UDP in the network.
In Java NIO, the core cache is as follows:
· Bytebuffer
· Charbuffer
· DoubleBuffer
· Floatbuffer
· Intbuffer
· Longbuffer
· Shortbuffer
These caches include the basic data types that send data over IO.
Java NiO also has a mappedbytebuffer that is used for memory file mapping.
Selector Selector
A selector allows a single thread to process data from multiple channels. This is handy if your app opens up a lot of connections (channel), but the traffic per connection (channel) is a little bit smaller. such as chat server.
A single thread handles three channels through a selector
First register the channel with the selector and then you call the Select () method, which blocks until a channel is ready for the event you register. Once the method returns, the thread can handle the event. Events can be connections, receiving data, and so on.
Here is a piece of code in advance, you readers, first look, the following will be slowly explained, the code will also have detailed comments
This code describes the selectors, registration and other related mechanisms.
"Java" "NiO" 2, Java NIO overview