首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java NIO Scatter/Gather 矢量 IO 實戰詳解

     編輯:Java 綜合教學

Java NIO Scatter/Gather 矢量 IO 實戰詳解

Scatter/Gather(分散/聚集)IO 允許單次系統調用操作多個 Buffer,減少數據拷貝與上下文切換,是高性能網絡編程的關鍵技術。

核心概念

  • Gather Write:多個 Buffer 依序發送,邏輯上等同合併為大 Buffer
  • Scatter Read:單次讀取按順序填滿多個 Buffer,直到數據耗盡或 Buffer 滿

適用場景:協議頭/體分離、消息分幀、零拷貝傳輸優化。

API 簽名

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();
    }
}

關鍵注意點

  1. 讀寫前後必須正確 flip()/clear()/compact() 管理 Buffer 狀態
  2. 部分傳輸時需循環調用直到 hasRemaining() == false
  3. Scatter Read 遇到 EOF 時,最後一個 Buffer 可能未填滿
  4. 配合 FileChannel.transferTo/From 可實現內核級零拷貝,性能更優

掌握 Scatter/Gather 能顯著提升協議解析、文件傳輸等場景的吞吐量與延遲表現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved