任何網路程式架構都會面臨一個問題:如何提供一個高效的buffer?比如我們想寫一個http server,那麼就需要不斷的從檔案中讀入資料,然後寫入到socket中,如:
byte[] buf=new byte[4096];
while(file.read(buf)){
mysocket.write(buf);
}
java.nio中引入了一個重要的類:ByteBuffer,來做這件事情。(我的直覺是它應該和ACE的MessageBlock作用很像,但是後來發現介面迥異。)
ByteBuffer是一個抽象類別,它有兩種實現:HeapByteBuffer 和 DirectByteBuffer。java.nio.ByteBuffer.allocate(int)返回的是HeapByteBuffer,java.nio.ByteBuffer.allocateDirect(int)返回的是DirectByteBuffer。
HeapByteBuffer分配在jvm的堆(如新生代)上,和其它對象一樣,由gc來掃描、回收。DirectByteBuffer則是通過底層的JNI向C Runtime Time通過malloc分配,在JVM的GC所管理的堆之外。
下面討論HeapByteBuffer。
每個HeapByteBuffer內部有一個byte[]儲存資料。這個byte[]在構造HeapByteBuffer的時候分配好,長度不會自動成長。
HeapByteBuffer內部有四個指標(offset):
capacity:內部這個byte數組的大小(byte[]的length)。
mark:相當於書籤,初始值為-1。需要設定的時候mark()一下,需要跳回去的時候用reset()方法。
position:指向下一個讀取/寫入位置。初始值為0,讀/寫 資料的時候自動往後挪這個指標。
limit:初始值等於 capacity。
它們始終滿足這樣的關係:mark
flip操作:用在讀寫操作轉換的時候。
limit = position;
position = 0;
mark = -1; //清理掉書籤
樣本用法:
buf.put(magic); // 先往buffer裡面寫入一個包頭(packet header)
in.read(buf); // 然後從另外一個input stream中讀入包體,並寫入到buffer中
buf.flip(); // Flip buffer。剛才是往ByteBuffer裡寫資料,下面要轉換成讀資料。
out.write(buf); // 把整個buffer裡的有效資料(包頭+包體)讀出來,寫入output stream中。
但是調用這個方法之前一定要注意,不要多調用了一次。比如,把上面的第三行代碼複製一遍,那麼
buf.put(magic); // 先往buffer裡面寫入一個包頭(packet header)
in.read(buf); // 然後從另外一個input stream中讀入包體,並寫入到buffer中
buf.flip(); // Flip buffer。position=0。
buf.flip(); // Flip buffer。limit=0!
out.write(buf); // 什麼也不會寫入。
假如讓你實現一個readfile這樣的函數,你會在函數的末尾調用buf.flip嗎?
void readfile(File f,ByteBuffer bb){
f.read(bb);
bb.flip(); //Do it or not do it ? That’s a question。
}
你會在這個函數的介面注釋那裡說“我沒調用flip!!!”嗎?
ByteBuffer的toArray()?
有時候,想把ByteBuffer轉成一個byte[],把它裡面的有效資料拿出來。但是可惜它並沒有一個toArray()這樣的方法。於是就需要手動copy一下。
ByteBuffer bb;
byte[] contentsOnly = Arrays.copyOf( bb.array(), bb.position() );
DirectByteBuffer的介面和HeapByteBuffer完全一樣,最大的區別就是記憶體位置不一樣。如果有大量的檔案需要以memory mapping的方式映射到記憶體中,那麼DirectByteBuffer明顯優於HeapByteBuffer。因為這部分記憶體不用被gc,所以降低了gc消耗。另外,HeapByteBuffer的緩衝區無法作為作業系統direct io api的緩衝區,因為它未必是按page size對齊的。
關於ByteBuffer的效能測試:
往ByteBuffer裡面寫Float:比較數組(new float[10000])、HeapByteBuffer、DirectByteBuffer的效能差距。
數組: 2.06 微秒
DirectByteBuffer:3.94 微秒
普通buffer: 16.88 微秒
測試環境:Java HotSpot(TM) 64-Bit Server VM (build 21.0-b17, mixed mode), windows 7 64bit。
測試代碼:
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();
}
}
轉自:http://www.udpwork.com/item/6095.html