Significantly reduces the time to clone a DatagramPacket.

This commit is contained in:
lubomir.marinov 2014-09-05 13:18:50 +00:00
parent fd616daa1c
commit a34e108b2d

View File

@ -51,24 +51,64 @@ public class MultiplexingDatagramSocket
*/ */
public static DatagramPacket clone(DatagramPacket p) public static DatagramPacket clone(DatagramPacket p)
{ {
byte[] data;
int off;
int len;
InetAddress address;
int port;
synchronized (p) synchronized (p)
{ {
byte[] data = p.getData().clone(); data = p.getData();
InetAddress address = p.getAddress(); off = p.getOffset();
int port = p.getPort(); len = p.getLength();
if ((address == null) || (port < 0)) // Clone the data.
{ {
return new DatagramPacket(data, p.getOffset(), p.getLength()); // The capacity of the specified p is preserved.
} byte[] dataClone = new byte[data.length];
else
{ // However, only copy the range of data starting with off and
return // spanning len number of bytes. Of course, preserve off and len
new DatagramPacket( // in addition to the capacity.
data, p.getOffset(), p.getLength(), if (len > 0)
address, port); {
int arraycopyOff, arraycopyLen;
// If off and/or len are going to cause an exception though,
// copy the whole data.
if ((off >= 0)
&& (off < data.length)
&& (off + len <= data.length))
{
arraycopyOff = off;
arraycopyLen = len;
}
else
{
arraycopyOff = 0;
arraycopyLen = data.length;
}
System.arraycopy(
data, arraycopyOff,
dataClone, arraycopyOff,
arraycopyLen);
}
data = dataClone;
} }
address = p.getAddress();
port = p.getPort();
} }
DatagramPacket c = new DatagramPacket(data, off, len);
if (address != null)
c.setAddress(address);
if (port >= 0)
c.setPort(port);
return c;
} }
/** /**