Java NIO(二)Scattering Reads and Gathering Writes

1.Scattering Reads

scatter(分散)是指數據從一個channel讀取到多個buffer中。

scatter

ByteBuffer header = ByteBuffer.allocate(128);

ByteBuffer body?? = ByteBuffer.allocate(1024);

ByteBuffer[] bufferArray = { header, body }

channel.read(bufferArray);

read()方法按照buffer在數組中的順序將從channel中讀取的數據寫入到buffer,當一個buffer被寫滿后,channel緊接著向另一個buffer中寫。


2.?Gathering Writes

gather(聚集)是指多個buffer的數據寫入到同一個channel。

gathering writes

ByteBuffer header = ByteBuffer.allocate(128);

ByteBuffer body?? = ByteBuffer.allocate(1024);

ByteBuffer[] bufferArray = { header, body };

channel.write(bufferArray);

write()方法會按照buffer在數組中的順序,將數據寫入到channel,注意只有position和limit之間的數據才會被寫入。因此,如果一個buffer的容量為128byte,但是僅僅包含58byte的數據,那么這58byte的數據將被寫入到channel中。因此與Scattering Reads相反,Gathering Writes能較好的處理動態消息。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容