Remove all pending write operation and performs them via
{@link ChannelHandlerContext#write(Object, ChannelPromise)}.

@return  {@link ChannelFuture} if something was written and {@code null}
if the {@link PendingWriteQueue} is empty.
174820
public ChannelFuture removeAndWriteAll() {
        assert ctx.executor().inEventLoop();

        if (isEmpty()) {
            return null;
        }

        ChannelPromise p = ctx.newPromise();
        PromiseCombiner combiner = new PromiseCombiner(ctx.executor());
        try {
            // It is possible for some of the written promises to trigger more writes. The new writes
            // will "revive" the queue, so we need to write them up until the queue is empty.
            for (PendingWrite write = head; write != null; write = head) {
                head = tail = null;
                size = 0;
                bytes = 0;

                while (write != null) {
                    PendingWrite next = write.next;
                    Object msg = write.msg;
                    ChannelPromise promise = write.promise;
                    recycle(write, false);
                    if (!(promise instanceof VoidChannelPromise)) {
                        combiner.add(promise);
                    }
                    ctx.write(msg, promise);
                    write = next;
                }
            }
            combiner.finish(p);
        } catch (Throwable cause) {
            p.setFailure(cause);
        }
        assertEmpty();
        return p;
    }
565295
void afterWrite(Runnable task) {
        writeBuffer.add(task);
        drainStatus.lazySet(REQUIRED);
        tryToDrainBuffers();
        notifyListener();
    }
1373081
void checkWriteSuspend(ChannelHandlerContext ctx, long delay, long queueSize) {
        if (queueSize > maxWriteSize || delay > maxWriteDelay) {
            setUserDefinedWritability(ctx, false);
        }
    }
97359
public void writeTo(WritableByteChannel channel) throws IOException {
        for (ByteBuffer buffer : toDirectByteBuffers()) {
            channel.write(buffer);
        }
    }
1324624
@Override
    public void write(PendingEvent event) {
        //State is set to sealed during a Transaction abort and the segment writer should not throw an {@link IllegalStateException} in such a case.
        checkState(StreamSegmentNameUtils.isTransactionSegment(segmentName) || !state.isAlreadySealed(), "Segment: %s is already sealed", segmentName);
        synchronized (writeOrderLock) {
            ClientConnection connection;
            try {
                // if connection is null getConnection() establishes a connection and retransmits all events in inflight
                // list.
                connection = Futures.getThrowingException(getConnection());
            } catch (SegmentSealedException | NoSuchSegmentException e) {
                // Add the event to inflight, this will be resent to the succesor during the execution of resendToSuccessorsCallback
                state.addToInflight(event);
                return;
            }
            long eventNumber = state.addToInflight(event);
            try {
                Append append = new Append(segmentName, writerId, eventNumber, 1, event.getData(), null, requestId);
                log.trace("Sending append request: {}", append);
                connection.send(append);
            } catch (ConnectionFailedException e) {
                log.warn("Connection " + writerId + " failed due to: ", e);
                reconnect(); // As the message is inflight, this will perform the retransmission.
            }
        }
    }
775968
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame) {
        if (channel == null) {
            throw new NullPointerException("channel");
        }
        return close(channel, frame, channel.newPromise());
    }
378129
@Override
	public BlockChannelWriter<MemorySegment> createBlockChannelWriter(FileIOChannel.ID channelID,
								LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException
	{
		checkState(!isShutdown.get(), "I/O-Manager is shut down.");
		return new AsynchronousBlockWriter(channelID, this.writers[channelID.getThreadNum()].requestQueue, returnQueue);
	}
1053184
public void startWrite() {
		SynchronizationPoint<NoException> sp;
		synchronized (this) {
			// if nobody is using the resource, we can start writing
			if (readers == 0 && !writer) {
				writer = true;
				return;
			}
			// someone is doing something, we need to block
			sp = new SynchronizationPoint<NoException>();
			if (writersWaiting == null) writersWaiting = new LinkedList<>();
			writersWaiting.add(sp);
		}
		sp.block(0);
	}
807722
private Deferred<ChannelBuffer> serialize() throws Exception {
    final long start = System.currentTimeMillis();
    // buffers and an array list to stored the deferreds
    final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
    final OutputStream output_stream = new ChannelBufferOutputStream(response);

    final JsonGenerator json = JSON.getFactory().createGenerator(output_stream);
    json.writeStartObject();
    json.writeFieldName("outputs");
    json.writeStartArray();

    // We want the serializer to execute serially so we need to create a callback
    // chain so that when one DPsResolver is finished, it triggers the next to
    // start serializing.
    final Deferred<Object> cb_chain = new Deferred<Object>();

    // default to the expressions if there, or fall back to the metrics
    final List<Output> outputs;
    if (query.getOutputs() == null || query.getOutputs().isEmpty()) {
      if (query.getExpressions() != null && !query.getExpressions().isEmpty()) {
        outputs = new ArrayList<Output>(query.getExpressions().size());
        for (final Expression exp : query.getExpressions()) {
          outputs.add(Output.Builder().setId(exp.getId()).build());
        }
      } else if (query.getMetrics() != null && !query.getMetrics().isEmpty()) {
        outputs = new ArrayList<Output>(query.getMetrics().size());
        for (final Metric metric : query.getMetrics()) {
          outputs.add(Output.Builder().setId(metric.getId()).build());
        }
      } else {
        throw new IllegalArgumentException(
            "How did we get here?? No metrics or expressions??");
      }
    } else {
      outputs = query.getOutputs();
    }

    for (final Output output : outputs) {
      if (expressions != null) {
        final ExpressionIterator it = expressions.get(output.getId());
        if (it != null) {
          cb_chain.addCallback(new SerializeExpressionIterator(tsdb, json, 
              output, it, ts_query));
          continue;
        }
      }

      if (query.getMetrics() != null && !query.getMetrics().isEmpty()) {
        final TSSubQuery sub = sub_queries.get(output.getId());
        if (sub != null) {
          final TimeSyncedIterator it = new TimeSyncedIterator(output.getId(), 
              sub.getFilterTagKs(), sub_query_results.get(output.getId()));
          cb_chain.addCallback(new SerializeSubIterator(tsdb, json, output, it));
          continue;
        }
      } else {
        LOG.warn("Couldn't find a variable matching: " + output.getId() + 
            " in query " + query);
      }
    }
  
    /** Final callback to close out the JSON array and return our results */
    class FinalCB implements Callback<ChannelBuffer, Object> {
      public ChannelBuffer call(final Object obj)
          throws Exception {
        json.writeEndArray();
        
//        ts_query.getQueryStats().setTimeSerialization(
//            DateTime.currentTimeMillis() - start);
        ts_query.getQueryStats().markSerializationSuccessful();

        // dump overall stats as an extra object in the array
//        if (true) {
//          final QueryStats stats = ts_query.getQueryStats();
//          json.writeFieldName("statsSummary");
//          json.writeStartObject();
//          //json.writeStringField("hostname", TSDB.getHostname());
//          //json.writeNumberField("runningQueries", stats.getNumRunningQueries());
//          json.writeNumberField("datapoints", stats.getAggregatedSize());
//          json.writeNumberField("rawDatapoints", stats.getSize());
//          //json.writeNumberField("rowsFetched", stats.getRowsFetched());
//          json.writeNumberField("aggregationTime", stats.getTimeAggregation());
//          json.writeNumberField("serializationTime", stats.getTimeSerialization());
//          json.writeNumberField("storageTime", stats.getTimeStorage());
//          json.writeNumberField("timeTotal", 
//              ((double)stats.getTimeTotal() / (double)1000000));
//          json.writeEndObject();
//        }
        
        // dump the original query
        if (true) {
          json.writeFieldName("query");
          json.writeObject(QueryExecutor.this.query);
        }
        // IMPORTANT Make sure the close the JSON array and the generator
        json.writeEndObject();
        json.close();
        return response;
      }
    }

    // trigger the callback chain here
    cb_chain.callback(null);
    return cb_chain.addCallback(new FinalCB());
  }
876380
public ChannelPromise remove() {
        assert ctx.executor().inEventLoop();
        PendingWrite write = head;
        if (write == null) {
            return null;
        }
        ChannelPromise promise = write.promise;
        ReferenceCountUtil.safeRelease(write.msg);
        recycle(write, true);
        return promise;
    }
879431
private void writeToNetwork(EngineConnection engineConnection) {
      final String methodName = "writeToNetwork";
      logger.entry(this, methodName, engineConnection);

        if (engineConnection.transport.pending() > 0) {
            ByteBuffer head = engineConnection.transport.head();
            int amount = head.remaining();
            engineConnection.channel.write(head, new NetworkWritePromiseImpl(this, amount, engineConnection));
            engineConnection.transport.pop(amount);
            engineConnection.transport.tick(System.currentTimeMillis());
        }

        logger.exit(this, methodName);
    }
588359
public ChannelFuture handshake(Channel channel) {
        if (channel == null) {
            throw new NullPointerException("channel");
        }
        return handshake(channel, channel.newPromise());
    }
1365620
public boolean removeWaitingWork(final T context) {
	write.lock();
	try {
	    boolean result = waitingWork.remove(context);
	    if (result) {
		workChanged.signalAll();
	    }
	    return result;
	} finally {
	    write.unlock();
	}
    }
1233499
public void removeAndFail(Throwable cause) {
        assert ctx.executor().inEventLoop();
        if (cause == null) {
            throw new NullPointerException("cause");
        }
        PendingWrite write = head;

        if (write == null) {
            return;
        }
        ReferenceCountUtil.safeRelease(write.msg);
        ChannelPromise promise = write.promise;
        safeFail(promise, cause);
        recycle(write, true);
    }
507392
public T pollReadyWork() {
	write.lock();
	try {
	    return workAvailable() ? waitingWork.poll() : null;
	} finally {
	    write.unlock();
	}
    }
129823
public boolean writeInbound(Object... msgs) {
        ensureOpen();
        if (msgs.length == 0) {
            return isNotEmpty(inboundMessages);
        }

        ChannelPipeline p = pipeline();
        for (Object m: msgs) {
            p.fireChannelRead(m);
        }

        flushInbound(false, voidPromise());
        return isNotEmpty(inboundMessages);
    }
1212547
public void add(Object msg, ChannelPromise promise) {
        assert ctx.executor().inEventLoop();
        if (msg == null) {
            throw new NullPointerException("msg");
        }
        if (promise == null) {
            throw new NullPointerException("promise");
        }
        // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering,
        // we should add them to the queue and let removeAndFailAll() fail them later.
        int messageSize = size(msg);

        PendingWrite write = PendingWrite.newInstance(msg, messageSize, promise);
        PendingWrite currentTail = tail;
        if (currentTail == null) {
            tail = head = write;
        } else {
            currentTail.next = write;
            tail = write;
        }
        size ++;
        bytes += messageSize;
        tracker.incrementPendingOutboundBytes(write.size);
    }