Java NIO Direct vs. non-direct buffers

Source: Internet
Author: User

Bytebuffer has two ways to create buffers:
static Bytebuffer allocate (int capacity)
static Bytebuffer allocatedirect (int capacity)
Both of these methods are methods for creating buffers,with direct buffers, the JVM virtual machine performs native IO operations directly on this buffer, that is, the VM avoids copying the contents of the buffer to the intermediate buffer (or copying the content from the intermediate buffer) before or after each call to the underlying operating system's native IO. Direct byte buffers are created using the Allocatedirect factory method in the upper method, and the buffers returned by this method are often more expensive to allocate and deallocate than the indirect buffers, and the contents of the direct buffers can reside outside the regular garbage collection heap, so Their impact on the content requirements of the application may not be obvious, so it is recommended that the direct buffers be primarily allocated to large, persistent buffers that are susceptible to native IO operations of the underlying system. In general, it is best to assign them only when the direct buffers can bring significant benefits in terms of program performance.
Direct buffers can also be created using mapping to map file regions directly into memory, and the implementation of the Java platform facilitates the creation of byte buffers directly from native code through JNI, if one of these buffers refers to an inaccessible area of memory. The view accesses the zone without changing the contents of the buffer and causes an indeterminate exception to be thrown during or at some time during the visit.
The byte buffer is a direct or non-direct buffer that can be determined by Bytebuffer's Isdirect method, which is provided to enable the display buffer management to be performed in performance-critical code.
Accessing binary data:
This class defines methods that read and write all other primitive type values except Boolean, which can be converted to and from the byte sequence according to the current byte order of the buffer and can be obtained and modified by the order method. The specific byte order is represented by an instance of the Byteorder class, and the initial order of the byte buffers is Big_endian (the order can refer to the Java memory model http://blog.csdn.net/silentbalanceyh/archive/ 2009/10/13/4661230.aspx). To access heterogeneous binary data, this class also defines a series of absolute and relative put and get methods for each type, and defines relative methods for types such as float, char, short, int, long, and double, which can refer to API content by itself. The index parameter of the absolute get and put method is defined by the byte, not by the type that is read and written.
In order to access homogeneous binary data (that is, a sequence of values of the same type), this class also defines a method that can create a view for a buffer of the specified type, where the view buffer is just another buffer whose content is supported by that byte buffer, changes in the contents of the byte buffer are visible in the view buffer, and vice versa The position, limit, and tag values of the two buffers are independent. There are three major advantages to using the view buffers:
View buffers are indexed not by bytes, but by the size of their type-specific values
View buffers provide a relative batch of put and get methods that can transmit sequential sequences of values between buffers and arrays or other buffers of the same type
The view buffer can be more efficient because it is a direct buffer when and only if its supported byte buffers are direct buffers.
In fact, Bytebuffer is inherited from the buffer class, which is stored in bytes, if you want to convert them to a string, you need to use Charset,charset is a character encoding, which provides a way to convert the byte stream into a character stream (decoding) and convert the string into a byte stream (encoding). There are three important properties for this class:
Capacity (capacity): Indicates how much data the buffer can hold
Limit: Indicates the location of the read-write cache and cannot read or write data over the location
Position (position): represents the Reading and writing unit of the next buffer, each time the cache is read and written, the position changes, the position is a non-negative integer

import java.io.fileinputstream;import java.io.fileoutputstream;import java.nio.bytebuffer; import java.nio.channels.filechannel;  public class quickcopy {     public static void main (string args[])  throws Exception{         fileinputstream fin = new fileinputstream ("D:/work/ Test.txt ");        fileoutputstream fout = new  FileOutputStream ("D:/work/output.txt");        filechannel  Inchannel = fin.getchannel ();        filechannel  Outchannel = fout.getchannel ();        bytebuffer  Buffer = bytebuffer.allocate (1024x768);         while (True) {             int ret = inchannel.read (buffer);             if ( ret == -1)                  break;             buffer.flip ();  //the method is the parent class buffer method              outchannel.write (buffer);             buffer.clear ();  //the method is the parent class buffer method         }     }}


The upper code allocates 1024 bytes of direct buffers and then copies the files using local copies, which should be more efficient than regular file copies, explaining several of the more commonly used methods of Bytebuffer classes "Here are no ways to allocate buffers":
Public abstract Bytebuffer Compact () throws Readonlybufferexception:
--the method compresses this buffer (optional), copies the bytes between the current position and bounds of the buffer to the beginning of the buffer, copies the bytes at index p = position () to index 0, copies the bytes at index n+1 to the position of index 1, and so on until index limit ()- The byte at 1 is copied to index n = limit ()-1-p, then the position of the buffer is set to n + 1, and its bounds are set to its capacity, and if the tag is defined, it is discarded. Set the position of the buffer to the number of bytes copied, not 0, so that you can call this method immediately after another relative put method is called.
Public abstract Bytebuffer Duplicate ():
--Creates a new byte buffer that shares the contents of this buffer, the contents of the new buffer will be the contents of this buffer, changes to the contents of this buffer are visible in the new buffer, and vice versa; the position, bounds, and tag values of the two buffers are independent of each other. The new buffer will have the same capacity, bounds, position, and tag values as this buffer. When and only if this buffer is direct, the new buffer is straightforward, and the new buffer is read-only when this buffer is read-only.
Public abstract Bytebuffer Slice ():
--Creates a new byte buffer whose contents are the shared subsequence of this buffer, where the contents of the new buffer begin at the current position of this buffer, where changes to the contents of this buffer are visible in the new buffer, and vice versa; the position, bounds, and tag values of the two buffers are independent of each other.
public abstract Bytebuffer Wrap (byte[] array):
--Wrapping a byte array into a buffer, the new buffer will be supported by a given byte array, that is, the buffer modification will cause the array to be modified, and vice versa. The capacity and bounds of the new buffer will be array.length, its position will be zero, its tag is indeterminate, its underlying implementation data will be the given array, and its array offset will be zero.
Here are a few examples of basic operations:

import java.nio.bytebuffer;import java.nio.charbuffer; public class basictype {     public static void main (string args[])  throws Exception{         //  creating bytebuffer       using byte arrays   byte[] bytes = new byte[10];         Bytebuffer buffer = bytebuffer.wrap (bytes);         //   Create character bytebuffer        bytebuffer charbuffer =  Bytebuffer.allocate (        charbuffer charbuffer2 =);  buffer.ascharbuffer ();        //  set the Get character type buffer         bytebuffer charbuffer3 = bytebuffer.allocate (100);         charbuffer3.putchar ((char) 123);         Charbuffer3.flip ();         char c = charbuffer3.getchar ();     }}


Above is a basic type of operation, the lookup API can see the basic operations related to the method provided inside the class

Import Java.nio.bytebuffer;import Java.nio.CharBuffer;        public class Stringbytebuffer {public static void main (string args[]) throws exception{//use Bytebuffer to store strings        Bytebuffer buffer = bytebuffer.allocate (100);        Charbuffer CBuffer = Buffer.ascharbuffer ();        Cbuffer.put ("Hello World");        Cbuffer.flip ();    String result = Cbuffer.tostring (); }}

2013-01-13

Java NIO Direct vs. non-direct buffers

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.