Less memory copy for OIO datagram transport
This commit is contained in:
parent
ee3ae043dc
commit
08107683b3
@ -28,6 +28,7 @@ import java.io.InterruptedIOException;
|
|||||||
import java.net.DatagramPacket;
|
import java.net.DatagramPacket;
|
||||||
import java.net.MulticastSocket;
|
import java.net.MulticastSocket;
|
||||||
import java.net.SocketAddress;
|
import java.net.SocketAddress;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
|
|
||||||
import org.jboss.netty.buffer.ChannelBuffer;
|
import org.jboss.netty.buffer.ChannelBuffer;
|
||||||
@ -113,16 +114,26 @@ class OioDatagramWorker implements Runnable {
|
|||||||
OioDatagramChannel channel, ChannelFuture future,
|
OioDatagramChannel channel, ChannelFuture future,
|
||||||
Object message, SocketAddress remoteAddress) {
|
Object message, SocketAddress remoteAddress) {
|
||||||
try {
|
try {
|
||||||
// FIXME: Avoid extra copy.
|
ChannelBuffer buf = (ChannelBuffer) message;
|
||||||
ChannelBuffer a = (ChannelBuffer) message;
|
int length = buf.readableBytes();
|
||||||
byte[] b = new byte[a.readableBytes()];
|
ByteBuffer nioBuf = buf.toByteBuffer();
|
||||||
a.getBytes(0, b);
|
DatagramPacket packet;
|
||||||
DatagramPacket packet = new DatagramPacket(b, b.length);
|
if (nioBuf.hasArray()) {
|
||||||
|
// Avoid copy if the buffer is backed by an array.
|
||||||
|
packet = new DatagramPacket(
|
||||||
|
nioBuf.array(), nioBuf.arrayOffset(), length);
|
||||||
|
} else {
|
||||||
|
// Otherwise it will be expensive.
|
||||||
|
byte[] arrayBuf = new byte[length];
|
||||||
|
buf.getBytes(0, arrayBuf);
|
||||||
|
packet = new DatagramPacket(arrayBuf, length);
|
||||||
|
}
|
||||||
|
|
||||||
if (remoteAddress != null) {
|
if (remoteAddress != null) {
|
||||||
packet.setSocketAddress(remoteAddress);
|
packet.setSocketAddress(remoteAddress);
|
||||||
}
|
}
|
||||||
channel.socket.send(packet);
|
channel.socket.send(packet);
|
||||||
fireWriteComplete(channel, b.length);
|
fireWriteComplete(channel, length);
|
||||||
future.setSuccess();
|
future.setSuccess();
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
future.setFailure(t);
|
future.setFailure(t);
|
||||||
|
Loading…
Reference in New Issue
Block a user