Java NIO (i)

Source: Internet
Author: User

Tag: Take number SOC must master maintain buffer buffers same nbsp Pre res

Http://wiki.jikexueyuan.com/project/java-nio-zh/java-nio-overview.html

Java nio,non-blocking IO02. Java NIO Overview

NIO contains the following core components:

    • Channels
    • Buffers
    • Selectors

With the channel, we can write the data from the channel to buffer, or we can write the data in buffer to the channel

There are a lot of channel,buffer types. Here are a few of the main examples:

    • FileChannel
    • Datagramchannel
    • Socketchanne
    • Serversocketchannel
    • Bytebuffer
    • Charbuffer
    • DoubleBuffer
    • Floatbuffer
    • Intbuffer
    • Longbuffer
    • Shortbuffer

NiO actually also contains a mappedbytesbuffer, typically used for memory-mapped files

Selectors allow single-threaded operation of multiple channels. This feature can be very helpful if you have a large number of links in your program and the IO bandwidth of each link is not high. such as chat server. Below is a single thread in which Slector maintains 3 channel:

To use selector, we have to register the channel with the selector, and then we can call the selector selectr () method. This method will go into blocking until there is a channel status that matches the condition.

. Java NIO Channel Channels

Java NIO channel channels and streams are very similar, mainly with the following differences:

    • The channel can also be written, flow is generally one-way (can only read or write).
    • Accessibility can be read and written asynchronously.
    • Channels are always read and written based on buffer buffers.

The most important implementation of the centralized channel in Java NIO:

    • Data read and write for filechannel files
    • Datagramchannel UDP data Read and write
    • Socketchannel TCP Data Read and write
    • Serversocketchannel listens for TCP link requests, and each request creates a Socketchannel

Example of using FileChannel to read data to buffer:

Randomaccessfile Afile =NewRandomaccessfile ("Data/nio-data.txt", "RW"); FileChannel Inchannel=Afile.getchannel (); Bytebuffer buf= Bytebuffer.allocate (48); intBytesread =Inchannel.read (BUF);//read data into buffer while(Bytesread! =-1) {System.out.println ("Read" +bytesread); Buf.flip ();//Use the Flip () method to adjust buffer from write mode to read mode while(Buf.hasremaining ()) {System.out.print (Char) Buf.get ());      } buf.clear (); Bytesread=Inchannel.read (BUF); } afile.close ();
Geneva. Java NIO Buffer Buffers

Using buffer to read and write data typically follows four steps:

    • Write data to buffer;
    • Call Flip;
    • reading data from buffer;
    • Call Buffer.clear () or buffer.compact ()

A buffer has three properties that must be mastered, namely:

    • Capacity capacity, can write up to the capacity of bytes, shaping and other data. Once the buffer is full, the read data needs to be emptied to continue writing the new data
    • Position location,
    • Limit limits

Capacity can write up to only the capacity of bytes, shaping and other data. Once the buffer is full, the read data needs to be emptied to continue writing the new data

Position: Where to begin reading and writing data. When writing data, the default is initialized to 0, each write to one byte or shaping data, position moves to the next cell, position the maximum value is capacity-1. When the data is read, the position is zeroed, and the position moves backwards after each read.

Limit

The maximum amount of data that can be written in write mode. Equivalent to the capacity of buffer.

Read mode, limit represents the maximum amount of data we can read, and his value is equal to the position of position in write mode.

Method of buffer:

1. Allocate memory: Allocate ().ByteBuffer.allocate(48)

2. Write data to buffer:

    • Write data from channel to bufferinChannel.read(buf)
    • Write data to buffer manually, call the Put methodbuf.put(127);

3. Read data from buffer:

    • Read data from buffer to channelinChannel.write(buf)
    • Read data directly from buffer, call the Get methodbyte aByte = buf.get(); 

4 Flip Flip (): Switch buffer from write mode to read mode. Calling the Flip method will return position to zero and set the value of the position before limit. That is, the position now represents the read position, and the limit indicates the location of the data being written.

5.rewind () resets the position to 0 so that we can read the data in buffer repeatedly. Limit remains unchanged.

6..clear () and compact ()

Difference: Keep the data or empty it all.

Clear (): Empty the entire buffer, the data is not empty, but the mark is changed. Position reset to 0, limit is capacity

Compact (): You can preserve unread data, empty only the data that has been read, and the unread data is moved to the beginning of the buffer, and the write location is followed by the unread data.

7. The mark () and reset () Mark method can mark the current position and restore Mark's position via reset

8.equals () and CompareTo ()

Equals ():

To determine the relative two buffer, you need to meet:

    • Same type
    • The same number of bytes remaining in buffer
    • All remaining bytes are equal

As can be seen from the above three conditions, equals only compares parts of buffer, and does not compare each element

CompareTo is also a comparison of the remaining elements in buffer, except that this method is suitable for comparison sorting:

Java NIO (i)

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.