Java NIO系列教程(四) Scatter/Gather
2016-12-15 21:52
405 查看
Java NIO系列教程(四) Scatter/Gather
原文地址:http://tutorials.jenkov.com/java-nio/scatter-gather.html作者:Jakob Jenkov 译者:郭蕾
Java NIO开始支持scatter/gather,scatter/gather用于描述从Channel(译者注:Channel在中文经常翻译为通道)中读取或者写入到Channel的操作。
分散(scatter)从Channel中读取是指在读操作时将读取的数据写入多个buffer中。因此,Channel将从Channel中读取的数据“分散(scatter)”到多个Buffer中。
聚集(gather)写入Channel是指在写操作时将多个buffer的数据写入同一个Channel,因此,Channel 将多个Buffer中的数据“聚集(gather)”后发送到Channel。
scatter / gather经常用于需要将传输的数据分开处理的场合,例如传输一个由消息头和消息体组成的消息,你可能会将消息体和消息头分散到不同的buffer中,这样你可以方便的处理消息头和消息体。
Scattering Reads
Scattering Reads是指数据从一个channel读取到多个buffer中。如下图描述:
Java NIO: Scattering Read
代码示例如下:
1 | ByteBuffer header = ByteBuffer.allocate( 128 ); |
2 | ByteBuffer body = ByteBuffer.allocate( 1024 ); |
3 |
4 | ByteBuffer[] bufferArray = { header, body }; |
5 |
6 | channel.read(bufferArray); |
Scattering Reads在移动下一个buffer前,必须填满当前的buffer,这也意味着它不适用于动态消息(译者注:消息大小不固定)。换句话说,如果存在消息头和消息体,消息头必须完成填充(例如 128byte),Scattering Reads才能正常工作。
Gathering Writes
Gathering Writes是指数据从多个buffer写入到同一个channel。如下图描述:
Java NIO: Gathering Write
代码示例如下:
1 | ByteBuffer header = ByteBuffer.allocate( 128 ); |
2 | ByteBuffer body = ByteBuffer.allocate( 1024 ); |
3 |
4 | //write data into buffers |
5 |
6 | ByteBuffer[] bufferArray = { header, body }; |
7 |
8 | channel.write(bufferArray); |
相关文章推荐
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(4):Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- 4.Java NIO系列教程之Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(四) Scatter/Gather