"Java" "NiO" 2, Java NIO overview

Source: Internet
Author: User

Java NiO mainly consists of the following core components:

    1. Channel
    2. Cache
    3. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.