Java NiO Buffering

Source: Internet
Author: User

First, preface

When I intend to learn the Netty framework, I find it necessary to learn NIO first, so we have this blog post, first of all, the buffer in NiO is introduced.

Second, buffer

  2.1 Hierarchy Chart

In addition to Boolean types, other primitive types have corresponding buffer classes, and their inheritance relationship hierarchy is as follows.

Where buffer is the parent class of all classes, the common behavior of all buffers is also specified in buffer.

  2.2 Buffer Base

  A buffer is an array of basic data elements wrapped within an object with four important attributes

    Capacity (capacity): The maximum number of data elements that a buffer can hold, the capacity is set when the buffer is created, and can never be changed.

Upper bound (Limit): The first element of a buffer that cannot be read or written. Or, the count of the existing elements in the buffer.

Position (Position): The index of the next element to be read or written. The location is automatically updated by the corresponding get () and put () functions.     

Mark: a memo location. Call Mark () to set mark = Postion. Call Reset () to set position = mark. The tag is undefined before setting (undefined).

The relationships between the four attributes are as follows

    0 <= Mark <= position <= limit <= capacity

A bytebuffer logical view with a capacity of 10 is shown.

  

Where Mark is not set, position initially 0,capacity to 10,limit as 10, the first element is stored to the position 0 position, capacity unchanged, and the other three properties change. When position calls put (), it automatically indicates where the next data element should be inserted, or when get () is called to indicate where the next element should be removed.

When you need to read the data after it is put, you need to call the flip function, which sets the limit to position, then sets the position to 0 and then starts reading.

When the flip function is called two times against a buffer, the size of the buffer becomes 0. Because the second limit is also set to 0,position to 0, the buffer size is 0.

  Buffers are not multithreaded safe. If you want to access a specific buffer at the same time as multiple threads, you need to synchronize before accessing the buffer.

Here is an example of a simple buffer read and write 

ImportJava.nio.CharBuffer;/*** Created by LEESF on 2017/4/15.*/ Public classBufferdemo { Public Static voidMain (string[] args) {Charbuffer buffer= Charbuffer.allocate (5); Buffer.put (H); Buffer.put (E); Buffer.put (L); Buffer.put (L); Buffer.put (O);        Buffer.flip ();  while(Buffer.hasremaining ()) {System.out.print (Buffer.get ()); }    }}

The operation results are as follows

HELLO

When comparing buffers, the same necessary and sufficient conditions for determining two buffers are as follows

· Two objects of the same type. Buffer with different data types will never be equal and buffer will never equal a non-buffer object.

· Two objects have the same number of elements remaining. The capacity of buffer does not need to be the same, and the index of the remaining data in the buffer does not have to be the same. However, the number of remaining elements in each buffer (from position to upper bound) must be the same.

· The sequence of remaining data elements that should be returned by the Get () function in each buffer must be consistent.

  If any of these conditions are not met, a comparison of two buffers returns false.

When two buffers are not the same length, a shorter buffer is considered to be less than the longer buffer if a buffer is exhausted before the unequal element is found.

  When the buffer interacts with the array, an exception is obtained if the data in the buffer is not sufficient to fully fill the array. This means that if you want to pass a small buffer into a large array, you must explicitly specify the remaining length of the data in the buffer. If the buffer has enough space to accept the data in the array (buffer.remaining () >myarray.length), the data will be copied to the buffer starting at the current position, and the buffer position will be increased by the number of data elements in advance. If there is not enough space in the buffer, no data is passed and the bufferoverflowexception exception is thrown.

  2.3 Creating buffers

  The new buffer is created by the Assign (allocate) or wrap (wrap) operation. The assign operation creates a buffer object and allocates a private space to store data of the specified capacity size. The wrapper operation creates a buffer object but does not allocate any space to store data elements, using the provided array as storage space to store the data in the buffer.

Use the allocation method to create the buffer as follows, such as creating a charbuffer with a capacity size of 100.  

Charbuffer Charbuffer = charbuffer.allocate (100);

Create a buffer using the wrapper method as follows

Char New Char [= Charbuffer.wrap (MyArray);

The code above constructs a new buffer object, but the data element is present in the array. This means that changes to the buffer caused by invoking the put () function directly affect the array, and any changes to the array will also be visible to the buffer object.

The Wrap () function version with offset and length as a parameter constructs a buffer that initializes the position and upper bound according to the specified offset and length parameter values.

Charbuffer Charbuffer = Charbuffer.wrap (MyArray, 12, 42);

The code above creates a buffer with a value of position, a limit of 54 (12 + 42), and a capacity of myarray.length.

2.4 Copy Buffer

When a buffer that manages the data elements contained by other buffers is created, the buffer is called the view buffer, and the view buffer is always created by invoking a function in the existing memory instance.

such as the duplicate () function creates a new buffer similar to the original buffer, two buffers share data elements, have the same capacity, but each buffer has its own position, upper bounds, and tag attributes. changes to the data elements in one buffer are reflected in the other buffer . This copy buffer has the same data view as the original buffer. If the original buffer is read-only, or is a direct buffer, the new buffers inherit these properties. That is, copying a buffer creates a new buffer object, but does not replicate the data, and both the original buffer and the copy manipulate the same data elements .

As in the following code snippet

Charbuffer buffer = charbuffer.allocate (8), Buffer.position (3). Limit (6). Mark (). Position (5=  Buffer.duplicate (); Buffer.clear ();

Creates a buffered view as shown

  

As you can see, the copied buffers inherit four property values, and the bottom of the operation is the same data, and the operation of each view on the data is reflected on another view, as the following code validates.

ImportJava.nio.CharBuffer;/*** Created by LEESF on 2017/4/13.*/ Public classAllocatedemo { Public Static voidMain (string[] args) {Charbuffer buffer= Charbuffer.allocate (8); Buffer.put (L); Buffer.put (E); Buffer.put (E); Buffer.put (S); Buffer.put (F); Buffer.position (3). Limit (6). Mark (). Position (5); Charbuffer Dupebuffer=buffer.duplicate ();        Buffer.clear ();        Dupebuffer.flip ();        System.out.println (Dupebuffer.position ());        System.out.println (Dupebuffer.limit ());        System.out.println (Dupebuffer.get ()); Buffer.put (Y); Buffer.put (D);        Buffer.flip ();        System.out.println (Buffer.position ());        System.out.println (Buffer.limit ());        System.out.println (Buffer.get ());    System.out.println (Dupebuffer.get ()); }}

The operation results are as follows

L-YD

You can see that the buffer view's write to the data affects the Dupebuffer data acquisition.

  2.5-byte buffers

Bytes are the basic data types used by the operating system and its I/O devices. When data is passed between the JVM and the operating system, it is also passed using a field.

Each base data type is stored in memory as a sequential sequence of bytes, such as the 32-bit int value 0x037fb4c7 (decimal 58,700,999) that may be stored in memory bytes as shown (the memory address is incremented from left to right).

  

The way multibyte values are stored in memory is generally referred to as endian-ness(byte order), if the highest byte of a numeric value--big end (big-endian) at the low address, then the system is the endian byte order, if the lowest byte is first saved in memory, Then the small-endian byte order, as shown in.

  

The default byte order is always Bytebuffer.big_endian, regardless of the inherent byte order of the system. the default byte order for Java is the big-endian byte order .

In order to solve the efficiency problem of non-direct buffers (such as the wrapped buffer created through the Wrap () function), direct buffers are introduced, and the memory used by the direct buffers is allocated by calling code on the local operating system, bypassing the standard JVM stack, and therefore more efficient. The Isdirect method exists in Bytebuffer to determine if the buffer is a direct buffer.

byte buffers can be converted to other different types of buffers, such as Charbuffer, Shortbuffer, and so on, and the converted buffers are simply views of the original buffers, which have independent four attribute values, but share data elements.

byte buffers can store or fetch different types of data elements directly, such as Direct put (char char), put (int value), and so on. When put, it converts different types of data into byte types from the position position, and then, when get, it takes the corresponding number of bytes from the position position to return after the conversion, starting with the different get types.

Iii. Summary

This blog post explains the buffer in NiO, the core is four properties, all the operations for the buffer is based on four attributes of the operation, the reader wants to more specific understanding of the contents of the buffer, you can consult the source code, thank you for the view of the Garden friends ~

Java NiO Buffering

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.