美文网首页
JAVA NIO Channels(三)

JAVA NIO Channels(三)

作者: ShootHzj | 来源:发表于2017-08-19 18:35 被阅读28次

    通道提供了分散聚合的能力。就是说一次IO操作可以对应多个buffer。

    对于写操作(向通道中写入数据),数据从数个buffer中汇合然后沿通道发送
    对于读操作(从通道中读出数据),从通道中出来的数据分散到许多不同的buffer,尽可能地读取,直到数据或者buffer的可用空间被耗尽。

    许多现代操作系统支持native vectored(矢量) IO;当你在一个通道上发起一个分散聚合请求时,请求会被解释成native方法。这样子buffer的复制和系统调用可以减少甚至消除。最好使用direct buffer,得到最优的性能。

    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个数据,body中有38个。

    相似的,我们可以组装数据在不同的buffer中,然后发送聚合

      body.clear();
      body.put("FOO".getBytes()).flip();
      header.clear();
      header.putShort(TYPE_FILE).putLong(body.limit()).flip();
      long bytesWritten = channel.write(buffers);
    

    相关文章

      网友评论

          本文标题:JAVA NIO Channels(三)

          本文链接:https://www.haomeiwen.com/subject/xwutdxtx.html