}
}
private void flush(ChannelHandlerContext ctx, boolean fireNow) throws Exception {
boolean acquired;
final Channel channel = ctx.getChannel();
boolean suspend = false;
flushNeeded = true;
// use CAS to see if the have flush already running, if so we don't need to take futher actions
if (acquired = flush.compareAndSet(false, true)) {
flushNeeded = false;
try {
if (!channel.isConnected()) {
discard(ctx, fireNow);
return;
}
while (channel.isWritable()) {
if (currentEvent == null) {
currentEvent = queue.poll();
}
if (currentEvent == null) {
break;
}
if (currentEvent.getFuture().isDone()) {
// Skip the current request because the previous partial write
// attempt for the current request has been failed.
currentEvent = null;
} else {
final MessageEvent currentEvent = this.currentEvent;
Object m = currentEvent.getMessage();
if (m instanceof ChunkedInput) {
final ChunkedInput chunks = (ChunkedInput) m;
Object chunk;
boolean endOfInput;
try {
chunk = chunks.nextChunk();
endOfInput = chunks.isEndOfInput();
if (chunk == null) {
chunk = ChannelBuffers.EMPTY_BUFFER;
// No need to suspend when reached at the end.
suspend = !endOfInput;
} else {
suspend = false;
}
} catch (Throwable t) {
this.currentEvent = null;
currentEvent.getFuture().setFailure(t);
if (fireNow) {
fireExceptionCaught(ctx, t);
} else {
fireExceptionCaughtLater(ctx, t);
}
closeInput(chunks);
break;
}
if (suspend) {
// ChunkedInput.nextChunk() returned null and it has
// not reached at the end of input. Let's wait until
// more chunks arrive. Nothing to write or notify.
break;
} else {
ChannelFuture writeFuture;
if (endOfInput) {
this.currentEvent = null;
writeFuture = currentEvent.getFuture();
// Register a listener which will close the input once the write
// is complete. This is needed because the Chunk may have some
// resource bound that can not be closed before its not written
//
// See https://github.com/netty/netty/issues/303
writeFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
closeInput(chunks);
}
});
} else {
writeFuture = future(channel);
writeFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
currentEvent.getFuture().setFailure(future.getCause());
closeInput((ChunkedInput) currentEvent.getMessage());
}
}
});
}
write(
ctx, writeFuture, chunk,
currentEvent.getRemoteAddress());
}
} else {
this.currentEvent = null;
ctx.sendDownstream(currentEvent);
}
}
if (!channel.isConnected()) {
discard(ctx, fireNow);
return;
}
}
} finally {
// mark the flush as done
flush.set(false);
}
}
if (acquired && (!channel.isConnected() || channel.isWritable() && !queue.isEmpty() && !suspend
|| flushNeeded)) {
flush(ctx, fireNow);
}
}