Java nio--buffer (buffer)

Source: Internet
Author: User
Tags compact rewind

Buffer is an abstract class that is located in the Java.nio package and is used primarily as a buffer. Note: Buffer is a non-thread-safe class.

A buffer is essentially a piece of memory in which data can be written and then read from it. This memory is packaged into a NiO buffer object and provides a set of methods for easy access to the block memory.

NIO has the following buffer types:

    • Bytebuffer
    • Mappedbytebuffer
    • Charbuffer
    • DoubleBuffer
    • Floatbuffer
    • Intbuffer
    • Longbuffer
    • Shortbuffer
Capacity

As a block of memory, buffer has a fixed size value, also known as "capacity". You can only write in capacity a byte, Long,char and other types. Once the buffer is full, it needs to be emptied (by reading the data or clearing the data) to continue writing the data.

Capacity once initialized
Will not change, its value is always constant. In use we generally use the abstract subclass Bytebuffer.allocate () method of buffer, which is actually the generation of the Bytearraybuffer class.

Position

When you write data into buffer, position represents the current position. The initial position value is 0. When a byte, long, and other data is written to buffer, the position moves forward to the next buffer cell that can insert the data. The position can be capacity–1 maximum.

When reading data, it is also read from a specific location. When the buffer is switched from write mode to read mode, the position is reset to 0. When the data is read from the position in buffer, the position moves forward to the next readable position.

Limit

In read mode, the limit of buffer indicates how much data you can read from buffer. Write mode, limit equals buffer's capacity.

When you switch buffer to read mode, limit indicates how much data you can read. Therefore, when you toggle buffer to read mode, limit is set to the position value in write mode. In other words, you can read all the previously written data (limit is set to the number of written data, this value is position in write mode)

(1) The variable meaning defined in buffer
/*** <code>UNSET_MARK</code> means the MARK has not been set.*/Static Final intUnset_mark =-1;/*** The capacity of this buffer, which never changes.*/Final intcapacity;/*** <code>limit-1</code> is, the last element, can be read or written. * Limit must being no less than ze RO and no greater than <code>capacity</code>. */intlimit;/*** Mark is where position'll be set if <code>reset () </code> is called. * mark was not set by default. M Ark is always no less than zero and no * greater than <code>position</code>. */intMark =Unset_mark;/*** The current position of this buffer. Position is always no less than zero * and no greater than <code>limit</code>. */intPosition = 0;/*** The log base 2 of the element size of this buffer.  Each typed subclass * (Bytebuffer, Charbuffer, etc) are responsible for initializing this * value. The value is used by JNI code in frameworks/base/to avoid the * need for costly ' instanceof ' tests. */Final int_elementsizeshift;/*** For direct buffers, the effective address of the the data; zero otherwise. * It is set in the constructor.*/Final Longeffectivedirectaddress;

(2) The Clear () method is used for write mode, which is to empty the contents of the buffer, so-called emptying refers to the write limit is the same as the real capacity of buffer, that is, limit==capacity, while the current write position is placed at the forefront of the subscript 0. The code is as follows:
/*** <code>UNSET_MARK</code> means the MARK has not been set.*/Static Final intUnset_mark =-1;/*** clears this buffer. * <p> * and the content of this buffer are not changed, the following internal * changes Take place:the current position are reset back to the start of * The buffer, the value of the buffer limit is made equal To the capacity * and Mark is cleared. * * @returnThis buffer.*/ Public FinalBuffer Clear () {position= 0;//set the current subscript to 0Mark = Unset_mark;//Cancellation TokenLimit = capacity;//setting write cross-over location same as buffer capacity    return  This;}

(3) The Reset () method is the same as the clear () method for write mode, except that reset () is used to discard the data after the mark position, start writing again from the mark position, and Mark cannot be set, and clear is re-written from the 0 position.
  • /*** Sets this buffer's mark at its position. * *@returnThis buffer*/ Public FinalBuffer mark () {Mark=position; return  This;}/*** Resets the position of this buffer to the <CODE>MARK</CODE>. *@returnThis buffer. *@throwsInvalidmarkexception * If the mark is not set.*/ Public FinalBuffer Reset () {if(Mark = =Unset_mark) {        Throw NewInvalidmarkexception ("Mark not set"); } position=Mark; return  This;}

(4) Rewind () is available in read/write mode, it simply resets the current position to 0, while canceling the mark Mark, which means that the limit remains the same as the buffer capacity in write mode, only to write again; limit is still in read mode with rewind () Call before the same, that is, flip () called before the last position of the position in write mode, after the flip () call this position changed to read the mode of the limit position, that is, the cross-border position, the code is as follows:
/**@return*/publicfinal  Buffer Rewind () {    = 0;     = Unset_mark;     return  This ;}

(5) The role of the flip () function is to convert the write mode to read mode, the final position of the content in the buffer in the write mode becomes the limit position in the read mode, as the read out of bounds position, while the current read position is set to 0, indicating that after the conversion to start reading, while eliminating the mark mark in write mode, The code is as follows
/**@return     */public final Buffer flip () {= position;     = 0;     = Unset_mark;     return  This ;}

(6) remaining () is used only in read mode to obtain the number of bytes that have not yet been read.
    • /** * Returns The number of remaining elements in this buffer, which is * {@code@return
           
            *
            /public
            final
            int 
             remaining ()    {
            return Limit-
             position;}
           

(7) The Compact () method of the abstract subclass of buffer Bytebuffer is also very important. The compact () function is to compress the data. For example, the current EOF is 6, the current pointer points to 2 (that is, 0,1 data has been written out, useless), then the compact method will move the 2,3,4,5 data to 0,1,2,3 position, and then the pointer points to 4 position. This means that the data is then written from the position of 4.
/** * Compacts this byte buffer. * <p> * The remaining bytes'll be moved to the head of the * buffer, starting FR Om position zero. Then the position are set to * {@code@return  {@code@ Throws  readonlybufferexception *                */publicabstract Bytebuffer Compact ();

(8) equals ()

Two buffer equals when the following conditions are met:

    • Have the same type (byte, char, int, and so on).
    • The remaining number of Byte, char, and so on in buffer is equal.
    • All remaining byte, char, and so on in buffer are the same.

Equals is only a part of the comparison buffer, not every element in it is compared (that is, it compares only the remaining elements in buffer).

Taking Bytebuffer as an example

  • /*** Tells whether or not this buffer is equal to another object. * <p>-byte buffers is equal if, and only If, * * <ol> * * <li><p> They has the same element type, </p></li> * * <li><p > They has the same number of remaining elements, and * </p></li> * <li><p> the other sequ Ences of remaining elements, considered * independently of their starting positions, is pointwise equal.  * </p></li> * * </ol> * * <p> A byte buffer is not equal to any other type of object. </p> * *@paramOB the object to which this buffer was to be compared * *@return<tt>true</tt> If, and only if, this buffer was equal to the * given object*/ Public Booleanequals (Object ob) {if( This==ob)return true; if(! (obinstanceofBytebuffer)) return false; Bytebuffer that=(bytebuffer) ob; if( This. Remaining ()! =that.remaining ())return false; intp = This. Position ();  for(inti = This. Limit ()-1, J = That.limit ()-1; I >= p; I--, j--)        if(!equals ( This. Get (i), That.get (j))) return false; return true;}

(9) CompareTo ()

The CompareTo () method compares the remaining elements of two buffer (byte, char, and so on) and considers a buffer "less than" another buffer if the following conditions are true:

    • The first unequal element is smaller than the corresponding element in the other buffer.
    • All elements are equal, but the first buffer is exhausted before the other (the number of elements in the first buffer is less than the other one).

Taking Bytebuffer as an example

  • /*** Compares this buffer to another. * * <p>-byte buffers is compared by comparing their sequences of * Rema Ining elements lexicographically, without regard to the starting * position of all sequence within its corresponding buff Er. * Pairs of {@codebyte} elements is compared as if by invoking * {@linkbyte#compare (Byte,byte)}. * * <p> A byte buffer is not comparable to any other type of object. * * @returna negative integer, zero, or a positive integer as this buffer * are less than, equal to, or greater than th e Given buffer*/ Public intCompareTo (Bytebuffer that) {intn = This. Position () + math.min ( This. Remaining (), that.remaining ());  for(inti = This. Position (), j = that.position (); I < n; i++, J + +) {        intCMP = Compare ( This. Get (i), That.get (j)); if(CMP! = 0)            returnCMP; }    return  This. Remaining ()-that.remaining ();}

Add:
    • Because the Bytebuffer is non-thread-safe, it must also be locked for multi-threaded access.

    • Bytebuffer internally also uses byte[] as a memory buffer, but provides more tag variables. When multi-threaded access, you can clearly know the location of the current data.

Reprint Source--http://blog.csdn.net/chy555chy/article

Java nio--buffer (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.