Scatter/Gather(分散/聚集)IO 允許單次系統調用操作多個 Buffer,減少數據拷貝與上下文切換,是高性能網絡編程的關鍵技術。
適用場景:協議頭/體分離、消息分幀、零拷貝傳輸優化。
long read(ByteBuffer[] dsts, int offset, int length) long write(ByteBuffer[] srcs, int offset, int length)
支持指定起始 Buffer 與數量,靈活控制參與向量操作的緩衝區範圍。
public static void channelGatherScatter() {
ByteBuffer header = ByteBuffer.allocate(4); // 固定 4 字節頭部
ByteBuffer body = ByteBuffer.allocate(100); // 體部緩衝區
ByteBuffer[] buffers = {header, body};
try (RandomAccessFile inFile = new RandomAccessFile("hello.txt", "r");
RandomAccessFile outFile = new RandomAccessFile("hehe.txt", "rw");
FileChannel inChannel = inFile.getChannel();
FileChannel outChannel = outFile.getChannel()) {
// Scatter Read: 讀取時自動按順序填充 header → body
while (inChannel.read(buffers) != -1) {
// 處理邏輯...
}
// 處理前需 flip 所有 Buffer
header.flip();
body.flip();
System.out.println("Header: " + new String(header.array()));
System.out.println("Body: " + new String(body.array()));
// Gather Write: 依序發送 header → body
while (outChannel.write(buffers) > 0) {
// 循環直到所有數據寫完
}
} catch (IOException e) {
e.printStackTrace();
}
}
flip()/clear()/compact() 管理 Buffer 狀態hasRemaining() == falseFileChannel.transferTo/From 可實現內核級零拷貝,性能更優掌握 Scatter/Gather 能顯著提升協議解析、文件傳輸等場景的吞吐量與延遲表現。