NIO Socket Programming Guide and study notes the Buffer

Buffer Buffer Introduction

In NIO Buffer is a container for storing the value of the basic data types, it is similar to the way an ordered array to store and organize data.

NIO art in the buffer, there are four points core technology, are:

  • capacity (capacity)
  • limit (limit)
  • position (position)
  • mark (mark)

The magnitude relation between the four point value art:

0 <= mark <= position <= limit <= capacity

Buffer capacity , which represents the number of elements contained. Buffer capacity can not be negative, and the capacity can not be changed.

Buffer limit , which represents a first element should not be read or written in index (index). Buffer limit (limit) can not be negative, and not greater than Capacity limit. If the new position is greater than the limit, then the position is set to the new limit. If the mark is defined and larger than the new limit, the mark is discarded.

Buffer position , which represents the "next" element to be read or written in index (index), the buffer position (location) can not be negative, and the position can not be greater than its limit. If the mark is defined and larger than the new position, discarding the mark.

method

  • int position (): returns the position of this buffer.
  • Buffer position (int newPosition): Set a new position of this buffer.
  • int remaining (): returns the number of elements between the "current position" and the limit.
  • Buffer mark ():. In this buffer position setting flag is a flag buffer index, when calling reset () method, the buffer will be reset for the index position location.
  • boolean isReadOnly (): inform this buffer is read-only buffer.
  • boolean isDirect (): This is determined whether the buffer is direct buffers.
  • final Buffer clear (): reducing buffer to the initial state , the position is set to contain 0, set the limit to the capacity, and discard flag, i.e., "all as Default" and "not really clear" data in the buffer. but the data are in a state of oblivion.
  • final Buffer flip (): This buffer inverted first limit to the current position, then the position is set to 0. If the flag has been defined, the tag is discarded.
  • final boolean hasArray (): This is determined whether the buffer has an accessible underlying array.
  • final boolean hasRemaining (): determining whether all elements between the current position and limitations.
  • final Buffer rewind (): rewind this buffer, and the position is set to 0 discard flag .rewin () method of the popular explanation is " flag cleared , the position values were normalized position 0, limit change." Note : rewind () method effect, is typically used when re-reading the data buffer.
  • final int arrayOffset (): Returns the bottom of this buffer to achieve a buffer offset of the first element of the array, this value is labeled "optional" in the document, i.e. subclasses may not process this value.

Comparative rewind (), clear (), flip () method

  • rewind (): the buffer is "re-read" data is included ready, it makes the limit remains unchanged, the position is set to 0.
  • clear (): make a series of new channel buffer is read or relative put (value) ready for operation, i.e., it is set to limit the size of the capacity, the position is set to 0.
  • flip (): make a series of new channel buffer is written or relatively get (value) ready for operation, i.e., limiting it to the current position, then the position is set to 0.

These three methods focus is on:

  1. rewind (): focus in the "re", re-reading, re-writing can be used;
  2. clear (): focus on "everything would also like to state";
  3. flip (): focus intercepting substring.

ByteBuffer

Buffer ByteBuffer class is a subclass of the class can access the data bytes in the buffer, but it is also relatively common and important class buffer.

Direct buffers

  1. Non-direct buffers

    Data to the disk by accessing ByteBuffer is temporarily stored in the intermediate data required to buffer the JVM, if there are frequent data operation occurs, each time the operating data are temporarily stored in the intermediate buffer the JVM, then to ByteBuffer processing, to do so would greatly reduce software for data throughput, improve memory share, resulting in lower operating efficiency of the software, which is non-direct buffers hold data process.

  2. Direct buffers

    JVM will try to execute directly on the buffer native I / O operations, i.e. directly on the kernel space access, to improve operating efficiency. Improve the operating efficiency of each principle is called before the operating system I / O operations on or after, JVM will try to avoid copying the contents of the buffer to the intermediate buffer, or copy the contents from the intermediate buffer, thus saving a step.

    Factory method by allocateDirect()time cost allocation and release of memory required to be returned to the buffer than the buffer indirect. Buffer data directly operated not JVM stack , but in the kernel space, this structure can be analyzed, direct buffers good saving those susceptible native operating system operation affects I O / lot, long-term storage of data .

    Buffer using a direct data exchange is achieved at both ends, in the kernel space directly proceeds the process without creating a new buffer JVM, thus reducing further the step of creating an intermediate buffer JVM, increasing the process efficiency.

method

  • allocateDirect (int capacity): slow to allocate new direct byte buffer. The new buffer will be zero, its limit will be its capacity, and its mark is uncertain. Whether or not it has the backing array, and its mark is uncertain. Created out of the buffer type DirectByteBuffer. Used allocateDirect()when creating ByteBuffer buffer method, capacity refers to the byte number, while creating IntBuffer buffer, capacity refers to the int number of values, if the byte to be converted, the capacity value is multiplied by 4, total number of bytes occupied calculated.

  • allocate (int capacity): allocating a non-direct byte buffer. The new buffer will be zero, its limit will be its capacity, and its mark is uncertain. It will have a backing array , and the data offset will be zero. Created out of the buffer type HeapByteBuffer.

  • wrap (byte [] array): The byte array into a buffer. The new buffer will be given byte array support, that is to say, lead to modifications to the buffer array to be modified, and vice versa.

  • wrap (byte [] array, int offset, int length): The byte array into a buffer. The new buffer will be given byte array support, that is, modifications to the buffer will cause the array to be modified , and vice versa. The new buffer's capacity will be array.length, its position will be offset, its limit will be offset + length, its mark will be undefined.

  • put (byte [] src, int offset, int length): Relative bulk put method that will transport a given source to a byte into this buffer from the current array location.

    • src: buffer location from the current data array src.
    • offset: the first byte to be read in the "offset array", and "not offset buffer", must be non-negative and no greater than src.length.
    • length: the number of bytes read from a given array, must be non-negative and no greater than src.length - offset.
  • get (byte [] dst, int offset, int length): Relative bulk get method, which buffer byte transfer this current position to a given destination array.

  • put (int index, byte b) : Absolute put method, the given byte into this buffer at the given index. position unchanged .

  • get (int index): Absolute get method, reads the byte at the specified location index. position unchanged .

  • put (ByteBuffer src): Relative bulk put method, this method is given the remaining source current byte into this buffer position in the buffer.

  • slice (): Creates a new byte buffer whose content is this buffer's content shared subsequence . Content of the new buffer will start at this buffer's current position. Changes to this buffer contents are visible in the new buffer, and vice versa; the two buffers, and the restriction flag independent.

  • asCharBuffer (): create a view of this byte buffer as a char buffer. Content of the new buffer will start at this buffer's current position. Changes to this buffer contents are visible in the new buffer, and vice versa; the two buffers, markers and limit values ​​are independent of each other. The new buffer will be zero, and limits the capacity for this half of the number of remaining bytes in the buffer, which marker is uncertain.

  • asReadOnlyBuffer (): create a shared buffer contents of this new read-only byte buffer. To this end the content of the new buffer contents of the buffer.

  • This byte compression buffer (optional operation), the bytes between the current position and limit buffer (if any) to the beginning of the buffer, i.e. the index p = position () at: compact () copied to index 0, the index of the byte copying p + 1 to the index 1, and so on until the () index limit - 1 bytes copied to the index n = limit () - 1-p at . Then, the buffer position is set to n + 1, and is set to its capacity limits. If the flag has been defined, it is discarded.

  • equals (): comparison is a position to limit the content is completely different.

  • compareTo (ByteBuffer that): this buffer is compared with another buffer. Comparison of two byte buffer is to compare their lexicographically sequences of remaining elements , regardless of the start position of each sequence in the corresponding buffer.

  • ByteBuffer duplicate (): create a shared buffer contents of this new byte buffer. To this end the content of the new buffer contents of the buffer. Changes to this buffer contents are visible in the new buffer, and vice versa.

    duplicate () method and the slice () method creates a new buffer object, but still using the buffer original buffer byte [] array of bytes .

A view buffer

  • asCharBuffer()
  • asDoubleBuffer()
  • asFloatBuffer()
  • asIntBuffer ()
  • asLongBuffer()
  • asShortBuffer()

A view buffer and ByteBufer has the following three advantages compared to:

  1. The view index byte buffers are, but indexed according to their size worth of type-specific.
  2. View buffer provides relative bulk get and put methods, these methods can be continuous sequence of values ​​transmitted between the buffer and the buffer array or other type of same.
  3. A view buffer may be more efficient, because if and only if it supports byte buffer when the buffer is direct, it is the direct buffer.

Set the byte order is obtained

CPU in an order different from the byte read is not the same, the CPU starts to read from some high, and starts reading from the CPU and some low, when the two CPU data transfer must be arranged in the order of byte unity, then order(ByteOrder bo)the method comes into play, its role is to set the order of the bytes.

What are the high and low it?

If 16-bit (two-byte) data, such as FF1A, the FF is high, a low 1A. If the 32-bit data, such 3F68415B, high word is 3F68, 415B is low word, is low on the right, the left is high.

Effect ByteOrder order () method: This buffer acquire byte order. Order byte buffer is always a new creation BIG_ENDIAN.

  1. public static final ByteOrder BIG_ENDIAN: represents a BIG_ENDIANconstant byte order. In this order, byte order from the multi-byte most significant bit to least significant bit.

  2. pulic static final ByteOrder LITTLE_ENDIAN: indicates LITTLE_ENDIANbyte order constant. In this order, byte order is multi-byte value from the least significant bit to most significant bit.

    order (ByteOrder bo): byte order to modify this buffer, in default, the initial order byte buffer is always BIG_ENDIAN.

CharBuffer

method

  • public CharBuffer append (char c): adding to this buffer (optional operation) specified character. Equivalent to:dst.put(c)
  • public CharBuffer append (CharSequence csq): The specified character sequence to this buffer (optional operation). Equivalent to:dst.put(csq.toString())
  • public CharBuffer append (CharSequence csq, int start, int end): is added to this buffer (optional operation) of the sub-specified character sequence. When csq is not null, the form of the called method is dst.append(csq, start, end)equivalent to: dst.put(csq.subSequence(start, end).toString()).
  • public final char charAt (int index): reads characters at the given index with respect to the current position.
  • put (String src): Relative bulk put method (optional operation). Equivalent dst.put(s, 0, s.length())to: .
  • int read (CharBuffer target): the current character in the buffer character tries to write to the specified character buffer.
  • subSequence (int start, int end): Creating represents the specified subsequence of this buffer, relative to the current position of the new character buffer. The new buffer will share this buffer, that is, if the contents of this buffer is variable, the modification will result in a buffer to another buffer is modified.
  • public static CharBuffer wrap (CharSequence csq, int start, int end): The sequence of characters into a buffer. The new read-only buffer will be the content of a given character sequence. The buffer capacity will csq.length (), its position will start, which limits will end, is marked undefined.
    • csq: the representative of a sequence of characters, from which the new character buffer created.
    • star: represents the first character you want to use the index must be non-negative and no larger than csq.length (). Location of the new buffer will be set to this value.
    • end: The index of the character after the last character to be used, it must not be less than the start and not more than csq.length (). The new buffer is set to this limit value. The return value is a new character buffer.
  • public final int length (): Returns the length of this character buffer. When the character buffer as character sequences, but the length between the position of the number of characters (including) and limiting (not included), that is equivalent to the length of the remaining ().

Reference: High Hongyan the "NIO with Socket Programming Guide"

Guess you like

Origin juejin.im/post/5d1c37146fb9a07ea6488ec4