通道提供了分散聚合的能力。就是說一次IO操作可以對(duì)應(yīng)多個(gè)buffer祠饺。
對(duì)于寫操作(向通道中寫入數(shù)據(jù)),數(shù)據(jù)從數(shù)個(gè)buffer中匯合然后沿通道發(fā)送
對(duì)于讀操作(從通道中讀出數(shù)據(jù)),從通道中出來的數(shù)據(jù)分散到許多不同的buffer祖今,盡可能地讀取歧斟,直到數(shù)據(jù)或者buffer的可用空間被耗盡紧武。
許多現(xiàn)代操作系統(tǒng)支持native vectored(矢量) IO击你;當(dāng)你在一個(gè)通道上發(fā)起一個(gè)分散聚合請(qǐng)求時(shí)玉组,請(qǐng)求會(huì)被解釋成native方法谎柄。這樣子buffer的復(fù)制和系統(tǒng)調(diào)用可以減少甚至消除。最好使用direct buffer惯雳,得到最優(yōu)的性能朝巫。
public interface ScatteringByteChannel extends ReadableByteChannel {
public long read(ByteBuffer[] dsts) throws IOException;
public long read(ByteBuffer[] dots,int offset, int length) throws IOException;
}
public interface GatheringByteChannel extends WritableByteChannel {
public long write(ByteBuffer[] srcs) throws IOException;
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
}
看看下面的代碼段
ByteBuffer header = ByteBuffer.allocateDirect(10);
ByteBuffer body = ByteBuffer.allocateDirect(80);
ByteBuffer[] buffers = {header, body};
int bytesRead = channel.read(buffers);
如果返回值bytesRead為48,那么head中擁有最先的10個(gè)數(shù)據(jù)石景,body中有38個(gè)劈猿。
相似的,我們可以組裝數(shù)據(jù)在不同的buffer中潮孽,然后發(fā)送聚合
body.clear();
body.put("FOO".getBytes()).flip();
header.clear();
header.putShort(TYPE_FILE).putLong(body.limit()).flip();
long bytesWritten = channel.write(buffers);