Java NiO begins to support Scatter/gather,scatter/gather used to describe the operation of reading or writing to channel from channel: Channel in Chinese often translated as channels.
Scatter (scatter) reads from channel refers to writing read data to multiple buffer during a read operation. Therefore, channel will "scatter (scatter)" The data read from channel to multiple buffer.
A clustered (gather) write Channel refers to writing multiple buffer data to the same Channel during a write operation, so Channel
The data in multiple buffer "aggregates (gather)" is sent to the channel.
Scatter gather is often used for situations where the data needed to be processed separately, such as a message that consists of a message header and a message body, you may be able to spread the message body and message headers into different buffer so that you can easily handle the message headers and the message body.
scattering reads
Scattering reads means that data is read from one channel to multiple buffer. The following figure describes:
The code example is as follows:
Bytebuffer Header = bytebuffer.allocate (128);
Bytebuffer Body = bytebuffer.allocate (1024);
Bytebuffer[] Bufferarray = {header, body};
Channel.read (Bufferarray);
Note that buffer is first inserted into the array, and then the array is used as an input parameter to Channel.read (). The read () method writes the data read from the channel to the buffer in the order in which the buffer is in the array, and when a buffer is filled, the channel is immediately written to another buffer.
Scattering reads must fill the current buffer before moving the next buffer, which means it does not apply to dynamic messages: The message size is not fixed. In other words, if there is a message header and a message body, the header must complete the fill (for example, 128byte), scattering reads to work properly.
Gathering writes
Gathering writes means that data is written from multiple buffer to the same channel. The following figure describes:
The code example is as follows:
Bytebuffer Header = bytebuffer.allocate (128);
Bytebuffer Body = bytebuffer.allocate (1024);
Write data into buffers
bytebuffer[] Bufferarray = {header, body};
Channel.write (Bufferarray);
The buffers array is the entry of the Write () method, and the write () method writes the data to the channel according to the order of the buffer in the array, noting that only the data between position and limit is written. Therefore, if the capacity of a buffer is 128byte, but only contains 58byte of data, then this 58byte of data will be written into the channel. So, contrary to scattering reads, gathering writes can handle dynamic messages better.