Java NIO (two) buffers (buffer)

Source: Internet
Author: User
Tags rewind

Buffer: A container for a particular base data type defined by the Java.nio package, all of which are subclasses of the buffer abstract class.

The buffer in Java NIO is primarily used to interact with the channels (channel) in NIO, where data is read from the channel (channels) into the buffer or from the buffer (channel). Below, I draw a schematic diagram, CHANENL direct contact with the data source or destination, buffer as a mediator, read the data from one channel, and then write the data to another channel.

 

Buffer is like an array that can hold multiple data of the same type. Depending on the data type (except for the Boolean), there are the following Buffer common subclasses:

Bytebuffer
Charbuffer
Shortbuffer
Intbuffer
Longbuffer
Floatbuffer
DoubleBuffer
These Buffer classes use similar methods for managing data, except that they manage different types of data. is to get a buffer object by using the following method:
static Xxxbuffer allocate (int capacity): Creates a Xxxbuffer object with a capacity of capacity, creating a bytebuffer with a capacity of 1024 as follows.

Bytebuffer buffer = bytebuffer.allocate (1024);

In front of the buffer is like a data, the actual buffer of the internal storage data is a corresponding type of array, see the source code as follows:

Other types of buffer are similar.

Several main properties of buffer:

Position: The next index to read or write data whose value cannot be negative cannot be greater than limit.

Limit: The first index that should not read or write data, that is, the data at limit cannot be read or written, and its value cannot be negative or greater than the total capacity.

Capacity: Maximum capacity to create buffer, cannot be negative, cannot be modified after creation.

  such as the definition of a super-class variable:

1. Create a buffer with a capacity of 10 (subscript 1-9, subscript 10 is not in buffer capacity) as follows:

  

position:0

Capacity:10

Limit:10

2. After writing the five elements to buffer in:

Position:5

Capacity:10

Limit:10

3. After converting to read mode using the Buffer.flip () function:

Position:5

Capacity:10

Limit:10

Mark marks an out-of-action position.

So there are: Mark <= position <= limit <= capacity

Several common functions of buffer:

Buffer Clear (): empties the buffer and returns a reference to the buffer

Buffer Flip (): Sets the bounds of the buffer to the current position and reloads the current position to 0

int capacity (): Returns the capacity size of Buffer

Boolean hasremaining (): Determines if there are elements in the buffer

int limit (): Returns the position of the bounds (limit) of the Buffer

Buffer limit (int n): Sets the buffer bounds to n and returns a buffer object with a new limit

Buffer Mark (): Sets the flag on the buffer

int position (): Returns the current position of the buffer position

Buffer position (int n): Sets the current position of the buffer to n and returns the modified buffer object

int remaining (): Returns the number of elements between position and limit

Buffer Reset (): Move position position to the location where Mark was previously set

Buffer Rewind (): Set the position to 0, cancel the setting mark

Here's a piece of code to see how the Position,capacity,limit changes after each method call:

 Public classbuffertest {@Test Public voidTest () {String str= "ABCDE"; //1. Assigning a buffer of a specified sizeBytebuffer buf = bytebuffer.allocate (1024); System.out.println ("-----------------Allocate ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); //2. Using put () to deposit data into the bufferBuf.put (Str.getbytes ()); System.out.println ("-----------------put ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); //3. Toggle Read Data ModeBuf.flip (); System.out.println ("-----------------Flip ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); //4. Using get () to read data from a buffer        byte[] DST =New byte[Buf.limit ()];        Buf.get (DST); System.out.println (NewString (DST, 0, dst.length)); System.out.println ("-----------------get ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); //5. Rewind (): Repeatable ReadBuf.rewind (); System.out.println ("-----------------Rewind ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); //6. Clear (): clears the buffer. But the data in the buffer is still there, but in the "forgotten" statebuf.clear (); System.out.println ("-----------------Clear ()----------------");        System.out.println (Buf.position ());        System.out.println (Buf.limit ());                System.out.println (Buf.capacity ()); System.out.println ((Char) Buf.get ()); }}

Operation Result:

-----------------Allocate ()----------------
0
1024
1024
-----------------put ()----------------
5
1024
1024
-----------------Flip ()----------------
0
5
1024
Abcde
-----------------get ()----------------
5
5
1024
-----------------Rewind ()----------------
0
5
1024
-----------------Clear ()----------------
0
1024
1024
A

How to access buffer:

Get the data in Buffer

Get (): reads a single byte

Get (byte[] DST): Bulk reads multiple bytes into DST

Get (int index): reads bytes at the specified index (does not move position)

  

put the data into Buffer

Put (Byte B): Writes the given single byte to the current position of the buffer

Put (byte[] src): writes bytes in SRC to the current position of the buffer

put (int index, BYTE b): writes the specified byte to the index position of the buffer (position is not moved)

Non-direct buffering and direct buffers (for byte buffers)

1. Non-direct buffers

Bytebuffer buf = bytebuffer.allocate (1024);

2. Direct buffer

Bytebuffer buf = bytebuffer.allocatedirect (1024);

The ① byte buffer is either direct or non-direct. If it is a direct byte buffer, the Java virtual machine tries its best to perform native I/O operations directly on this buffer. That is, the virtual machine tries to avoid copying the contents of the buffer into the intermediate buffer (or copying the contents from the buffer in between) before each call to a native I/O operation of the underlying operating system.

The ② direct byte buffer can be created by calling the Allocatedirect () factory method of this class. The buffer returned by this method is typically higher than the non-direct buffer for allocation and deallocation. The contents of the direct buffers can reside outside the regular garbage collection heap, so their impact on the memory requirements of the application may not be obvious. Therefore, it is recommended that the direct buffers be allocated primarily to large, persistent buffers that are susceptible to native I/O operations of the underlying system. In general, it is best to assign them only if the direct buffers can bring significant benefits in terms of program performance.

The ③ direct byte buffer can also be created by mapping the file area directly into memory through the FileChannel map () method. The method returns Mappedbytebuffer. The implementation of the Java platform facilitates the creation of direct byte buffers from native code through JNI. If a buffer instance in these buffers refers to an inaccessible area of memory, attempting to access the zone does not change the contents of the buffer and will cause an indeterminate exception to be thrown during or at a later time during the visit.

The ④ byte buffer is either a direct buffer or a non-direct buffer that can be determined by calling its Isdirect () method. This method is provided for the ability to perform explicit buffer management in performance-critical code.

References: Li Hofei Teacher's video tutorial

Java NIO (two) buffers (buffer)

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.