Any Network Program Framework will face a problem: how to provide an efficient buffer? For example, if we want to write an HTTP server, we need to constantly read data from the file and write it into the socket, for example:
Byte [] Buf = new byte [1, 4096];
While (file. Read (BUF )){
Mysocket. Write (BUF );
}
Java. Nio introduces an important class: bytebuffer to do this. (My intuition is that it should be very similar to the messageblock function of ACE, but later I found that the interface is quite different .)
Bytebuffer is an abstract class, which has two implementations: heapbytebuffer and directbytebuffer. Java. NiO. bytebuffer. Allocate (INT) returns heapbytebuffer, java. NiO. bytebuffer. allocatedirect (INT) returns directbytebuffer.
Heapbytebuffer is allocated to the JVM heap (such as the new generation). Like other objects, it is scanned and recycled by GC. Directbytebuffer is allocated to C Runtime through malloc through the underlying JNI, outside the heap managed by jvm gc.
The following describes heapbytebuffer.
Each heapbytebuffer contains a byte [] to store data. This byte [] is allocated when heapbytebuffer is constructed, and the length will not automatically increase.
Heapbytebuffer has four internal pointers (offset ):
Capacity: The size of the byte array (length of byte ).
MARK: equivalent to bookmarks. The initial value is-1. Mark () when you need to set it, and use the reset () method when you need to jump back.
Position: point to the next read/write location. The initial value is 0. This pointer is automatically moved back when data is read/written.
Limit: the initial value is equal to capacity.
They always meet the following relationship: Mark
Flip operation: used for read/write operation conversion.
Limit = position;
Position = 0;
Mark =-1; // clear bookmarks
Example usage:
Buf. Put (MAGIC); // write a packet header to the buffer first)
In. Read (BUF); // then read the package body from another input stream and write it to the buffer.
Buf. Flip (); // flip buffer. I wrote data to bytebuffer just now. Below I want to convert it into read data.
Out. Write (BUF); // read the valid data (packet header + package body) in the buffer and write it into the output stream.
But before calling this method, be sure not to call it once more. For example, if you copy the third line of code
Buf. Put (MAGIC); // write a packet header to the buffer first)
In. Read (BUF); // then read the package body from another input stream and write it to the buffer.
Buf. Flip (); // flip buffer. Position = 0.
Buf. Flip (); // flip buffer. Limit = 0!
Out. Write (BUF); // nothing will be written.
If you want to implement a function such as readfile, will you call Buf. Flip at the end of the function?
Void readfile (file F, bytebuffer bb ){
F. Read (bb );
BB. Flip (); // do it or not do it? That's a question.
}
You will comment on this function interface and say, "I didn't call Flip !!!" ?
Bytebuffer toarray ()?
Sometimes, you want to convert bytebuffer into a byte [] and take out the valid data in it. But unfortunately, it does not have a toarray () method. So you need to manually copy the file.
Bytebuffer BB;
Byte [] contentsonly = arrays. copyof (BB. Array (), BB. Position ());
The directbytebuffer interface is exactly the same as heapbytebuffer. The biggest difference is that the memory location is different. If a large number of files need to be mapped to the memory in Memory Mapping mode, directbytebuffer is significantly better than heapbytebuffer. Because this part of memory does not need to be GC, GC consumption is reduced. In addition, the cache of heapbytebuffer cannot be used as the cache of the operating system direct Io API, because it may not be aligned by page size.
About bytebuffer performance testing:
Write float to bytebuffer: compares the performance gaps between arrays (new float [10000]), heapbytebuffer, and directbytebuffer.
Array: 2.06 microseconds
Directbytebuffer: 3.94 microseconds
Normal Buffer: 16.88 microseconds
Test environment: Java hotspot (TM) 64-bit server VM (build 21.0-b17, mixed mode), Windows 7 64bit.
Test code:
Private Final floatbuffer bytebuffer2 = bytebuffer. Allocate (40000). Order (byteorder. nativeorder ())
. Asfloatbuffer ();
Private Final floatbuffer bytebuffer = bytebuffer. allocatedirect (40000). Order (byteorder. nativeorder ())
. Asfloatbuffer ();
Protected void testwrite (){
// Allow VM to compile
Testwritearray (1000 );
Testwritebytebuffer (1000 );
// Test for real
System. Out. println ("Array Buffer:" + testwritearray (50000) + "US per iteration ");
System. Out. println ("direct Buffer:" + testwritebytebuffer (50000) + "US per iteration ");
}
Protected double testwritebytebuffer (INT iterations ){
Long timenow = system. currenttimemillis ();
For (Int J = 0; j For (INT I = 0; I bytebuffer. Put (I, 1234.5678f );
}
}
Return 1000.0 * (system. currenttimemillis ()-timenow)/iterations;
}
Protected double testwritearray (INT iterations ){
Long timenow = system. currenttimemillis ();
For (Int J = 0; j For (INT I = 0; I bytebuffer2.put (I, 1234.5678f );
}
}
Return 1000.0 * (system. currenttimemillis ()-timenow)/iterations;
}
Public buffermark (){
}
Public static void main (string [] ARGs ){
For (INT n = 0; n system. Out. println ("= round" + n );
Buffermark APP = new buffermark ();
App. testwrite ();
}
}
From: http://www.udpwork.com/item/6095.html