diff --git a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java index 634a38875d..bbeec19585 100644 --- a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java +++ b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java @@ -134,10 +134,7 @@ public class ChunkedWriteHandler extends ChannelDuplexHandler { @Override public void flush(ChannelHandlerContext ctx) throws Exception { - if (!doFlush(ctx)) { - // Make sure to flush at least once. - ctx.flush(); - } + doFlush(ctx); } @Override @@ -195,14 +192,14 @@ public class ChunkedWriteHandler extends ChannelDuplexHandler { } } - private boolean doFlush(final ChannelHandlerContext ctx) throws Exception { + private void doFlush(final ChannelHandlerContext ctx) throws Exception { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null); - return false; + return; } - boolean flushed = false; + boolean requiresFlush = true; ByteBufAllocator allocator = ctx.alloc(); while (channel.isWritable()) { if (currentWrite == null) { @@ -300,22 +297,24 @@ public class ChunkedWriteHandler extends ChannelDuplexHandler { } }); } + // Flush each chunk to conserve memory + ctx.flush(); + requiresFlush = false; } else { ctx.write(pendingMessage, currentWrite.promise); this.currentWrite = null; + requiresFlush = true; } - // Always need to flush - ctx.flush(); - flushed = true; - if (!channel.isActive()) { discard(new ClosedChannelException()); break; } } - return flushed; + if (requiresFlush) { + ctx.flush(); + } } static void closeInput(ChunkedInput chunks) { diff --git a/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java b/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java index 04b841dc94..66b69516fc 100644 --- a/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java @@ -98,6 +98,13 @@ public class ChunkedWriteHandlerTest { check(new ChunkedNioFile(TMP), new ChunkedNioFile(TMP), new ChunkedNioFile(TMP)); } + @Test + public void testUnchunkedData() throws IOException { + check(Unpooled.wrappedBuffer(BYTES)); + + check(Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES)); + } + // Test case which shows that there is not a bug like stated here: // http://stackoverflow.com/a/10426305 @Test @@ -220,10 +227,10 @@ public class ChunkedWriteHandlerTest { assertNull(ch.readOutbound()); } - private static void check(ChunkedInput... inputs) { + private static void check(Object... inputs) { EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler()); - for (ChunkedInput input: inputs) { + for (Object input: inputs) { ch.writeOutbound(input); }