Example usage for io.netty.util ReferenceCountUtil safeRelease

List of usage examples for io.netty.util ReferenceCountUtil safeRelease

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil safeRelease.

Prototype

public static void safeRelease(Object msg) 

Source Link

Document

Try to call ReferenceCounted#release() if the specified message implements ReferenceCounted .

Usage

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private ChannelFuture doWriteUnsplitData(ChannelHandlerContext ctx, int id, HttpData data, boolean endStream) {
    final ByteBuf buf = toByteBuf(ctx, data);
    boolean handled = false;
    try {//from   w ww. j a  v a  2 s.  c o  m
        final HttpContent content;
        if (endStream) {
            content = new DefaultLastHttpContent(buf);
        } else {
            content = new DefaultHttpContent(buf);
        }

        final ChannelFuture future = write(ctx, id, content, endStream);
        handled = true;
        ctx.flush();
        return future;
    } finally {
        if (!handled) {
            ReferenceCountUtil.safeRelease(buf);
        }
    }
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private ChannelFuture doWriteSplitData(ChannelHandlerContext ctx, int id, HttpData data, boolean endStream) {

    try {/* w  ww .  ja v a 2  s  .  com*/
        int offset = data.offset();
        int remaining = data.length();
        ChannelFuture lastFuture;
        for (;;) {
            // Ensure an HttpContent does not exceed the maximum length of a cleartext TLS record.
            final int chunkSize = Math.min(MAX_TLS_DATA_LENGTH, remaining);
            lastFuture = write(ctx, id, new DefaultHttpContent(dataChunk(data, offset, chunkSize)), false);
            remaining -= chunkSize;
            if (remaining == 0) {
                break;
            }
            offset += chunkSize;
        }

        if (endStream) {
            lastFuture = write(ctx, id, LastHttpContent.EMPTY_LAST_CONTENT, true);
        }

        ctx.flush();
        return lastFuture;
    } finally {
        ReferenceCountUtil.safeRelease(data);
    }
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private ChannelFuture write(ChannelHandlerContext ctx, int id, HttpObject obj, boolean endStream) {
    if (id < currentId) {
        // Attempted to write something on a finished request/response; discard.
        // e.g. the request already timed out.
        ReferenceCountUtil.safeRelease(obj);
        return ctx.newFailedFuture(ClosedPublisherException.get());
    }//ww  w . ja  va  2  s.c  o m

    final PendingWrites currentPendingWrites = pendingWritesMap.get(id);
    if (id == currentId) {
        if (currentPendingWrites != null) {
            pendingWritesMap.remove(id);
            flushPendingWrites(ctx, currentPendingWrites);
        }

        final ChannelFuture future = ctx.write(obj);
        if (endStream) {
            currentId++;

            // The next PendingWrites might be complete already.
            for (;;) {
                final PendingWrites nextPendingWrites = pendingWritesMap.get(currentId);
                if (nextPendingWrites == null) {
                    break;
                }

                flushPendingWrites(ctx, nextPendingWrites);
                if (!nextPendingWrites.isEndOfStream()) {
                    break;
                }

                pendingWritesMap.remove(currentId);
                currentId++;
            }
        }

        return future;
    } else {
        final ChannelPromise promise = ctx.newPromise();
        final Entry<HttpObject, ChannelPromise> entry = new SimpleImmutableEntry<>(obj, promise);
        final PendingWrites pendingWrites;
        if (currentPendingWrites == null) {
            pendingWrites = new PendingWrites();
            maxIdWithPendingWrites = Math.max(maxIdWithPendingWrites, id);
            pendingWritesMap.put(id, pendingWrites);
        } else {
            pendingWrites = currentPendingWrites;
        }

        pendingWrites.add(entry);

        if (endStream) {
            pendingWrites.setEndOfStream();
        }

        return promise;
    }
}

From source file:com.linecorp.armeria.internal.Http2ObjectEncoder.java

License:Apache License

@Override
protected ChannelFuture doWriteData(ChannelHandlerContext ctx, int id, int streamId, HttpData data,
        boolean endStream) {

    final ChannelFuture future = validateStream(ctx, streamId);
    if (future != null) {
        ReferenceCountUtil.safeRelease(data);
        return future;
    }//  ww w .  j a v  a 2s .co m

    return encoder.writeData(ctx, streamId, toByteBuf(ctx, data), 0, endStream, ctx.newPromise());
}

From source file:com.linecorp.armeria.internal.HttpObjectEncoder.java

License:Apache License

/**
 * Writes an {@link HttpData}./*from w w  w  .j av a2s  . c  o  m*/
 */
public final ChannelFuture writeData(ChannelHandlerContext ctx, int id, int streamId, HttpData data,
        boolean endStream) {

    assert ctx.channel().eventLoop().inEventLoop();

    if (closed) {
        ReferenceCountUtil.safeRelease(data);
        return newFailedFuture(ctx);
    }

    return doWriteData(ctx, id, streamId, data, endStream);
}

From source file:com.linecorp.armeria.internal.PooledObjects.java

License:Apache License

private static <T> T copyAndRelease(ByteBufHolder o) {
    try {//  w  w w .  ja  v  a  2s .co m
        final ByteBuf content = Unpooled.wrappedBuffer(ByteBufUtil.getBytes(o.content()));
        @SuppressWarnings("unchecked")
        final T copy = (T) o.replace(content);
        return copy;
    } finally {
        ReferenceCountUtil.safeRelease(o);
    }
}

From source file:com.linecorp.armeria.internal.PooledObjects.java

License:Apache License

private static <T> T copyAndRelease(ByteBuf o) {
    try {/*  www . j  a va 2 s .c  om*/
        @SuppressWarnings("unchecked")
        final T copy = (T) Unpooled.copiedBuffer(o);
        return copy;
    } finally {
        ReferenceCountUtil.safeRelease(o);
    }
}

From source file:com.linecorp.armeria.server.HttpResponseSubscriber.java

License:Apache License

@Override
public void onNext(HttpObject o) {
    if (!(o instanceof HttpData) && !(o instanceof HttpHeaders)) {
        throw newIllegalStateException("published an HttpObject that's neither HttpHeaders nor HttpData: " + o
                + " (service: " + service() + ')');
    }/*w w  w.ja v a2 s.  co m*/

    boolean endOfStream = o.isEndOfStream();
    switch (state) {
    case NEEDS_HEADERS: {
        logBuilder().startResponse();
        if (!(o instanceof HttpHeaders)) {
            throw newIllegalStateException("published an HttpData without a preceding Http2Headers: " + o
                    + " (service: " + service() + ')');
        }

        final HttpHeaders headers = (HttpHeaders) o;
        final HttpStatus status = headers.status();
        if (status == null) {
            throw newIllegalStateException(
                    "published an HttpHeaders without status: " + o + " (service: " + service() + ')');
        }

        if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
            // Needs non-informational headers.
            break;
        }

        final int statusCode = status.code();
        logBuilder().responseHeaders(headers);

        if (req.method() == HttpMethod.HEAD) {
            // HEAD responses always close the stream with the initial headers, even if not explicitly
            // set.
            endOfStream = true;
            break;
        }

        switch (statusCode) {
        case 204:
        case 205:
        case 304:
            // These responses are not allowed to have content so we always close the stream even if
            // not explicitly set.
            endOfStream = true;
            break;
        default:
            state = State.NEEDS_DATA_OR_TRAILING_HEADERS;
        }
        break;
    }
    case NEEDS_DATA_OR_TRAILING_HEADERS: {
        if (o instanceof HttpHeaders) {
            final HttpHeaders trailingHeaders = (HttpHeaders) o;
            if (trailingHeaders.status() != null) {
                throw newIllegalStateException(
                        "published a trailing HttpHeaders with status: " + o + " (service: " + service() + ')');
            }

            // Trailing headers always end the stream even if not explicitly set.
            endOfStream = true;
        }
        break;
    }
    case DONE:
        ReferenceCountUtil.safeRelease(o);
        return;
    }

    write(o, endOfStream);
}

From source file:com.yahoo.pulsar.broker.service.PulsarStats.java

License:Apache License

@Override
public void close() {
    ReferenceCountUtil.safeRelease(topicStatsBuf);
    ReferenceCountUtil.safeRelease(tempTopicStatsBuf);
}

From source file:com.yahoo.pulsar.client.impl.ProducerImpl.java

License:Apache License

void ackReceived(ClientCnx cnx, long sequenceId, long ledgerId, long entryId) {
    OpSendMsg op = null;//from w w w  . j  ava2s .c om
    boolean callback = false;
    synchronized (this) {
        op = pendingMessages.peek();
        if (op == null) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] Got ack for timed out msg {}", topic, producerName, sequenceId);
            }
            return;
        }

        long expectedSequenceId = op.sequenceId;
        if (sequenceId > expectedSequenceId) {
            log.warn("[{}] [{}] Got ack for msg. expecting: {} - got: {} - queue-size: {}", topic, producerName,
                    expectedSequenceId, sequenceId, pendingMessages.size());
            // Force connection closing so that messages can be retransmitted in a new connection
            cnx.channel().close();
        } else if (sequenceId < expectedSequenceId) {
            // Ignoring the ack since it's referring to a message that has already timed out.
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] Got ack for timed out msg {} last-seq: {}", topic, producerName,
                        sequenceId, expectedSequenceId);
            }
        } else {
            // Message was persisted correctly
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] Received ack for msg {} ", topic, producerName, sequenceId);
            }
            pendingMessages.remove();
            semaphore.release(op.numMessagesInBatch);
            callback = true;
            pendingCallbacks.add(op);
        }
    }
    if (callback) {
        op = pendingCallbacks.poll();
        if (op != null) {
            op.setMessageId(ledgerId, entryId, partitionIndex);
            try {
                // Need to protect ourselves from any exception being thrown in the future handler from the
                // application
                op.callback.sendComplete(null);
            } catch (Throwable t) {
                log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic,
                        producerName, sequenceId, t);
            }
            ReferenceCountUtil.safeRelease(op.cmd);
            op.recycle();
        }
    }
}