}
public static Buffer allocateAndReadBuffer(final TCPNIOConnection connection)
throws IOException {
final MemoryManager memoryManager =
connection.getTransport().getMemoryManager();
int read;
Throwable error = null;
Buffer buffer = null;
try {
final int receiveBufferSize =
Math.min(TCPNIOTransport.MAX_RECEIVE_BUFFER_SIZE,
connection.getReadBufferSize());
if (!memoryManager.willAllocateDirect(receiveBufferSize)) {
final DirectByteBufferRecord ioRecord =
DirectByteBufferRecord.get();
final ByteBuffer directByteBuffer =
ioRecord.allocate(receiveBufferSize);
try {
read = readSimpleByteBuffer(connection, directByteBuffer);
if (read > 0) {
directByteBuffer.flip();
buffer = memoryManager.allocate(read);
buffer.put(directByteBuffer);
}
} finally {
ioRecord.release();
}
} else {
buffer = memoryManager.allocateAtLeast(receiveBufferSize);
read = readBuffer(connection, buffer);
}
} catch (Throwable e) {
error = e;
read = -1;