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中,适合动态数据 

  • 相关阅读:
    远程支付技术方案
    软件架构设计(第2版)——程序员向架构师转型必备
    概念架构是什么
    项目报警机制
    编写有效用例
    移动支付的基本要素
    相机的日常维护和保养注意事项
    吴炜摄影教程随堂笔记1
    D80使用心得3
    项目沟通管理识别干系人
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/10022839.html
Copyright © 2011-2022 走看看