我正在阅读Hadoop IPC实现。
https://github.com/apache/hadoop/blob/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
逻辑是,如果缓冲区很小,它会读/写一次通道。如果缓冲区很大,它将多次执行,并且每次读/写8kb。
我不理解javadocs以及为什么要这样做。为什么“这是为了避免jdk随着缓冲区大小的增加创建许多直接缓冲区”?大缓冲区大小是否也会影响读取性能?
我理解缓冲区大小如何影响FileInputStream性能(link)。但这里是SocketChannel。所以它无关。
/**
* When the read or write buffer size is larger than this limit, i/o will be
* done in chunks of this size. Most RPC requests and responses would be
* be smaller.
*/
private static int NIO_BUFFER_LIMIT = 8*1024; //should not be more than 64KB.
/**
* This is a wrapper around {@link WritableByteChannel#write(ByteBuffer)}.
* If the amount of data is large, it writes to channel in smaller chunks.
* This is to avoid jdk from creating many direct buffers as the size of
* buffer increases. This also minimizes extra copies in NIO layer
* as a result of multiple write operations required to write a large
* buffer.
*
* @see WritableByteChannel#write(ByteBuffer)
*/
private int channelWrite(WritableByteChannel channel,
ByteBuffer buffer) throws IOException {
int count = (buffer.remaining() <= NIO_BUFFER_LIMIT) ?
channel.write(buffer) : channelIO(null, channel, buffer);
if (count > 0) {
rpcMetrics.incrSentBytes(count);
}
return count;
}
/**
* This is a wrapper around {@link ReadableByteChannel#read(ByteBuffer)}.
* If the amount of data is large, it writes to channel in smaller chunks.
* This is to avoid jdk from creating many direct buffers as the size of
* ByteBuffer increases. There should not be any performance degredation.
*
* @see ReadableByteChannel#read(ByteBuffer)
*/
private int channelRead(ReadableByteChannel channel,
ByteBuffer buffer) throws IOException {
int count = (buffer.remaining() <= NIO_BUFFER_LIMIT) ?
channel.read(buffer) : channelIO(channel, null, buffer);
if (count > 0) {
rpcMetrics.incrReceivedBytes(count);
}
return count;
}
逻辑是,如果缓冲区很小,它会读/写一次通道。如果缓冲区很大,它将多次执行,并且每次读/写8kb。
我不理解javadocs以及为什么要这样做。为什么“这是为了避免jdk随着缓冲区大小的增加创建许多直接缓冲区”?大缓冲区大小是否也会影响读取性能?
我理解缓冲区大小如何影响FileInputStream性能(link)。但这里是SocketChannel。所以它无关。