Avoid unnecessary coping.

This commit is contained in:
boris 2014-09-03 14:34:38 +00:00
parent 9c70d917de
commit 3b7a913eac

View File

@ -10,6 +10,7 @@ package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.logging.*;
/** /**
* Represents a <tt>Socket</tt> which receives <tt>DatagramPacket</tt>s * Represents a <tt>Socket</tt> which receives <tt>DatagramPacket</tt>s
@ -26,6 +27,12 @@ import java.util.*;
public class MultiplexedSocket public class MultiplexedSocket
extends DelegatingSocket extends DelegatingSocket
{ {
/**
* The <tt>Logger</tt> used by the <tt>MultiplexedSocket</tt> class
* and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(MultiplexedSocket.class.getName());
/** /**
* The <tt>DatagramPacketFilter</tt> which determines which * The <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network by {@link #multiplexing} * <tt>DatagramPacket</tt>s read from the network by {@link #multiplexing}
@ -166,11 +173,6 @@ public class MultiplexedSocket
*/ */
private final DatagramPacket packet = new DatagramPacket(buf, 1500); private final DatagramPacket packet = new DatagramPacket(buf, 1500);
/**
* Synchronization object for read operation.
*/
private final Object readSyncRoot = new Object();
/** /**
* Initializes a new <tt>TCPInputStream</tt>. * Initializes a new <tt>TCPInputStream</tt>.
*/ */
@ -213,22 +215,35 @@ public class MultiplexedSocket
public int read(byte[] b, int off, int len) public int read(byte[] b, int off, int len)
throws IOException throws IOException
{ {
synchronized(readSyncRoot) if (off == 0) // optimization: avoid copy to b
{ {
packet.setData(b);
receive(packet); receive(packet);
byte[] packetData = packet.getData(); int lengthRead = packet.getLength();
int packetOff = packet.getOffset(); if (packet.getData() == b && lengthRead <= len)
int packetLen = packet.getLength(); return lengthRead;
else
int lengthRead = Math.min(len, packetLen); logger.warning("Failed to read directly into the provided"
System.arraycopy( + " buffer, len=" + len + " lengthRead="
packetData, packetOff, + lengthRead + " (packet.getData() == b)="
b, off, + (packet.getData() == b));
lengthRead);
return lengthRead;
} }
// either there's an offset to take into account, or receiving
// directly in 'b' failed.
packet.setData(buf);
receive(packet);
int packetLen = packet.getLength();
int lengthRead = Math.min(len, packetLen);
System.arraycopy(
packet.getData(), packet.getOffset(),
b, off,
lengthRead);
return lengthRead;
} }
/** /**