通道有一个重要的功能,被称为Scatter/Gather(即矢量IO),它是指在多个缓冲区上实现一个简单的I/O操作。用通俗的话来说,就是在write的时候,可以将多个缓冲区中的数据写入一个更大的缓冲区中,然后沿着通道发送;在read的时候,将数据写入多个缓冲区中,将每个缓冲区填满,直到缓冲区的最大空间被消耗完。
当请求一个Scatter/Gather操作时,请请求会被翻译为适当的本地调用来直接填充或抽取缓冲区,这将减少或避免了缓冲区拷贝和系统调用。Scatter/Gather应该使用直接的ByteBuffer以从本地I/O获取最大性能。
Scatter操作:
ByteBuffer header = ByteBuffer.allocateDirect(10);
ByteBuffer body = ByteBuffer.allocateDirect(80);
ByteBuffer[] buffers = {header, body};
int bytesRead = channel.read(buffers);
Gather操作:
body.clear();
body.put("Foo".getBytes()).flip();
header.clear();
header.putShort(1).putLong(body.limit()).flip();
long bytesWritten = channel.write(buffers);
注意在填充完数据后,一定要调用flip方法,不然通道是读不到数据的。
package com.nio.channel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class Marketing {
private static final String DEMOGRAPHIC = "blahblah.txt";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int reps = 10;
if(args.length > 0) {
reps = Integer.parseInt(args[0]);
}
FileOutputStream fos = new FileOutputStream(DEMOGRAPHIC);
GatheringByteChannel gatherChannel = fos.getChannel();
ByteBuffer[] bs = utterBS(reps);
while(gatherChannel.write(bs) > 0) {
}
System.out.println();
fos.close();
}
private static String[] col1 = {
"Aggregate","Enable","Leverage",
"Facilitate", "Synergize","Repurepose",
"Strategize","collaborative","integrated"
};
private static String[] col2 = {
"croll-platform", "best-of-head","frictionless",
"ubiquitous","extensible","compelling",
"mission-critical","collaborative","integrated"
};
private static String[] col3 = {
"methodologies", "infomediaries","platforms",
"schema","mindshare","paradigms",
"functionalities","webservices","infrastructures"
};
private static String newline = System.getProperty("line.separator");
private static ByteBuffer[] utterBS(int howMany) throws Exception {
List list = new LinkedList();
for(int i = 0; i < howMany; i++) {
list.add(pickRandom(col1," "));
list.add(pickRandom(col2, " "));
list.add(pickRandom(col3, " "));
}
ByteBuffer[] bufs = new ByteBuffer[list.size()];
list.toArray(bufs);
return bufs;
}
private static Random rand = new Random();
private static ByteBuffer pickRandom(String[] strings, String suffix) throws Exception {
String string = strings[rand.nextInt(strings.length)];
int total = string.length() + suffix.length();
ByteBuffer buf = ByteBuffer.allocate(total);
buf.put(string.getBytes("UTF-8"));
buf.put(suffix.getBytes("UTF-8"));
buf.flip();
return buf;
}
}