Java NIO(二):Scatter 与 Gather

Scatter

  • 分散(Scatter)是指 Channel 将数据写入多个 Buffer 中
Scatter
  • 只有当第一个 Buffer 被写满后,Channel 才会将剩余的数据写入下一个 Buffer,这意味着它不适用于动态消息(消息大小不固定)
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = { header, body };
channel.read(bufferArray);

Gather

  • 聚集(Gather)是指将多个 Buffer 的写入同一个 Channel
Gather
  • 写入时会按照 Buffer 在数组中的顺序,将数据写入到 Channel,注意只有 position 和 limit 之间的数据才会被写入,假设一个 Buffer 容量 128 byte 但只包含 58 byte 的数据,那么只写入这 58 byte 到 Channel 中,因此 Gather 能较好的处理动态消息
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = { header, body };
channel.write(bufferArray);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容