Reduce copying for outbound messages, work on
@@ -478,13 +478,35 @@ public class TcpEventHandler<T extends NetworkContext<T>>
if (wrote < 0) {
close();
} else if (wrote > 0) {
- outBB.compact().flip();
+ if (outBB.hasRemaining()) {
+ if (shouldCompactOutBB(outBB)) {
+ outBB.compact()
+ .flip();
outBBB.writePosition(outBB.limit());
- return true;
+ outBBB.readPosition(0);
+ }
+ } else {
+ // We have written everything in the
+ // Buffer to the socket so we can
+ // restart at the beginning of the Buffer again
+ outBB.clear();
+ outBBB.writePosition(0); // This sets the readPosition to zero too
+ }
}
return false;
}
+ private boolean shouldCompactOutBB(final ByteBuffer bb) {
+ // Only compact if we can regain at least 25% the
+ // Buffer. This prevents massive successive copying
+ // of messages if the socket is stalled and only accepts
+ // a limited number of bytes on each write attempt. See #85
+ // As a drawback, this will reduce the effective buffer size
+ // by 25%.
+ return bb.position() >= bb.capacity() / 4;
+ //return outBBB.readPosition() >= outBBB.capacity() / 2;
+ }
+
public boolean writeAction() {
boolean busy = false;
