Java NiO Buffers

Source: Internet
Author: User

    • Brief introduction
      • IO Concepts
        • Buffer operation
        • Virtual memory
        • File IO
        • Stream IO
    • Buffer
      • Buffer Property
      • Buffer data fills, flips, releases, compresses, marks
      • Buffer comparison
      • Buffer Bulk Move
      • Copy buffer
    • byte buffers
      • Direct buffers
      • Other buffers
Brief introduction

And then the story about Javaweb, about NiO, on this: Javaweb story.
Several IO facts:

    1. Limiting factors that affect application execution efficiency, often non-processing rates, but IO
    2. The OS moves large chunks of data, often with DMA assistance, while the JVM's IO operations tend to be small pieces of data, and with NIO, that can change the situation
    3. Jdk1.4,java.nio provides a new set of abstractions for IO processing
IO Concept buffer operation

The process performs an IO operation, either draining the buffer data (read) or filling the buffer with data (write).
The process uses a read () system call that requires its buffers to be filled, the kernel randomly sends commands to the disk control hardware, writes the data to the kernel memory buffer with DMA (without primary CPU assistance), and once the disk controller fills the buffer, The kernel copies the data from the temporary buffer in the kernel space to the buffer that is executed when the process read () is called.

Among them 用户空间和内核空间 :
User space is the area of a regular process, such as a JVM. Kernel space is the area of the operating system, has special power, can communicate with the device controller, and control the running state of the user zone process.总之,所有IO都直接或间接通过内核空间。
The hardware does not have direct access to the user space, and the hardware device operates on a fixed-size block of data, and the user process may request any size or non-aligned block of data.

Virtual memory

The use of virtual addresses instead of physical memory addresses, there are two major types of benefits, one is that multiple virtual addresses point to the same physical address, and the second is that the virtual memory space can be larger than the hardware memory.

File IO

Unlike disk, file systems are high-level abstractions and are a unique way of arranging and interpreting disk or other random access block device data.
File system data is also cached in the same way as other memory pages, and for subsequent IO requests, some or all of the file data may still be in physical memory without needing to be read from disk.

文件锁定: Divided into shared and exclusive. Multiple shared locks can function on the same file area at the same time, and exclusive locks require that the relevant area cannot have other locks in effect.

Stream IO

The principle mimics the channel, which must be sequentially accessed, such as a console device and a printer port.

Buffer

The buffer class is the basis of the NIO construction, a buffer object is a fixed number of data containers, where the data is sadly stored and later used for retrieval. Can be understood as a transit point for data in I/O operations. Buffers are directly served by channels (channel), write data to the channel, or read data from the channel, so that the data can be transferred by using buffer data to achieve the purpose of efficient processing.

Buffer Property

Capacity capacity: Set at creation time, cannot be changed.
Upper bound limit: not readable or writable. The count of the existing elements.
Position position: The next index to be read or write elements.
Mark Mark: a memo location.

Buffer data fills, flips, releases, compresses, marks

The Java.nio.Buffer class is an abstract class that cannot be instantiated. The direct subclasses of the buffer class, such as Bytebuffer, are also abstract classes, so they cannot be instantiated.
But the Bytebuffer class provides a static factory method to get an instance of Bytebuffer, and finally it's time to show Code =. =, as follows:

               //InitializeBytebuffer buffer = Bytebuffer.Allocate(1024x768);//Data fillBuffer.put((byte) ' H '.put((byte) ' E '.put((byte) ' L '.put((byte) ' L '.put((byte) ' O '; System. out.println(buffer.toString());//java.nio.heapbytebuffer[pos=5 lim=1024 cap=1024]System. out.println((Char) (buffer.Get(0)));//h        //Data modificationBuffer.put(0, (byte) ' M '.put((byte) ' W '); System. out.println(buffer.toString());//java.nio.heapbytebuffer[pos=6 lim=1024 cap=1024]System. out.println((Char) (buffer.Get(0)));//m        //flip the position to 0 and flips a buffer to be filled to prepare the readout stateSystem. out.println(buffer);//java.nio.heapbytebuffer[pos=6 lim=1024 cap=1024]Buffer.Flip();//buffer.rewind ();//similar to flip, but does not affect the limit attribute. Java.nio.heapbytebuffer[pos=0 lim=1024 cap=1024]System. out.println(buffer);//java.nio.heapbytebuffer[pos=0 lim=6 cap=1024]        //Use Hasremaining () to determine if the upper bound of the buffer is reached         while(buffer.hasremaining()) {System. out.Print((Char) (buffer.Get())); }//mellowSystem. out.println("");//compression, compact discards freed data, preserves data not releasedBuffer.Compact();//mark, in a location tag, the reset () function sets the position to the current tag value.         if the tag value is undefined, calling reset () causes the invalidmarkexception exception.         ///Some buffer functions discard already set tokens (rewind (), clear (), and flip () always discard tags). Buffer.position(2).Mark();
Buffer comparison

Compare two buffers, Bytebuffer has implemented comparable interface, the source code is as follows:

  Public int CompareTo(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(); }Private Static int Compare(byteXbyteY) {returnByte.Compare(x, y); }
Buffer Bulk Move
        //批量取        bytenewbyte[1000];        buffer.get(myArray);        //等价于:        buffer.get0, myArray.length);        //批量存        bytenewbyte[1000];        buffer.put(myString);        //等价于:        buffer.put(myString,0,myString.length);
Copy buffer

Using the duplicate () function to copy a buffer, a new buffer object is created, but the data is not copied, and both the original buffer and the copy manipulate the same data elements.

byte buffers

All basic data types have corresponding buffer classes (except Booleans), byte types are special, and bytes are the basic type used by the operating system and its IO devices.
The base type of a non-byte type is also a combination of bytes, such as char2 bytes, int4 bytes, and double8 bytes. The combined bytes are sequential, and the Java default byte order is the big endian byte order, see Class Byteoreder.

Direct buffers

The byte buffer can be the source or destination of the IO executed by the channel, and the non-byte buffer is passed to the channel, which implicitly executes the copied content to a temporary bytebuffer, so the direct buffer is the best choice for IO.
The Isdirect () function is passed to determine if the buffer is a direct buffer.

Other buffers

The view buffer, which maintains its own properties, capacity, position, upper bounds, and tags, but shares data elements with the original buffer.
CharBuffer charBuffer = byteBuffer.asCharBuffer( );

The Bytebuffer class provides access and conversion methods for each primitive data type, such as the Getint () function being called, and the 4 bytes starting at the current position are wrapped in an int type variable to be returned.
For unsigned data, self-realization, pay attention to the accuracy problem.

The above from the operation Director of the day group: Kun Less

Java NiO Buffers

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.