zoukankan      html  css  js  c++  java
  • Java NIO Scatter/Gather(五)

    原文链接:http://tutorials.jenkov.com/java-nio/scatter-gather.html,如有侵权,立删

    Java NIO Scatter/Gather

    • Scattering Reads
    • Gathering Writes 

      Java NIO引入了 Scatter 和 Gather,这两个概念使用于向channel写入数据和从channel读取数据用的。

      scattering是和读操作有关的,channel将数据读取到多个buffer中去,channel分散数据到多个buffer中。

      gathering是个写操作有关的,将多个buffer中的数据写入到channel中去。

      scattering和gathering是非常有用的,在一些情形下。例如你需要传输不同的数据模块。

     scattering Reads

      一个scattering read从单个channel中读取数据到多个buffer中。上图

                            

    1 ByteBuffer header = ByteBuffer.allocate(128);
    2 ByteBuffer body   = ByteBuffer.allocate(1024);
    3 
    4 ByteBuffer[] bufferArray = { header, body };
    5 
    6 channel.read(bufferArray);

      要想向第二个buffer中写入数据,只能把第一个buffer写满。所以scattering read不适合动态数据,适合固定的数据大小的写入。

     Gathering Writes 

      上图

                            

    ByteBuffer header = ByteBuffer.allocate(128);
    ByteBuffer body   = ByteBuffer.allocate(1024);
    
    //write data into buffers
    
    ByteBuffer[] bufferArray = { header, body };
    
    channel.write(bufferArray);

      只有在position和limit之间的数据会被写入到channel中,适合动态数据 

  • 相关阅读:
    CentOS 7 修改国内yum源
    k8s 安装
    python2 python3同时安装了scrapy如何区分调用
    scrapy log 设置
    hello django
    linux 分割大文件
    scrapy 对不同的Item进行分开存储
    纯C实现的一套low b 贪吃蛇(娱乐版)
    Python之如何实现一行输入多个值
    HDU2571:命运(DP)
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/10022839.html
Copyright © 2011-2022 走看看