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.yahoo.pulsar.client.impl.ProducerImpl.java

License:Apache License

/**
 * Checks message checksum to retry if message was corrupted while sending to broker. Recomputes checksum of the
 * message header-payload again.//from   ww  w.  j  ava  2s. c o  m
 * <ul>
 * <li><b>if matches with existing checksum</b>: it means message was corrupt while sending to broker. So, resend message</li>
 * <li><b>if doesn't match with existing checksum</b>: it means message is already corrupt and can't retry again. So, fail
 * send-message by failing callback</li>
 * </ul>
 * 
 * @param cnx
 * @param sequenceId
 */
protected synchronized void recoverChecksumError(ClientCnx cnx, long sequenceId) {
    OpSendMsg op = pendingMessages.peek();
    if (op == null) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] [{}] Got send failure for timed out msg {}", topic, producerName, sequenceId);
        }
    } else {
        long expectedSequenceId = op.sequenceId;
        if (sequenceId == expectedSequenceId) {
            boolean corrupted = !verifyLocalBufferIsNotCorrupted(op);
            if (corrupted) {
                // remove message from pendingMessages queue and fail callback
                pendingMessages.remove();
                semaphore.release(op.numMessagesInBatch);
                try {
                    op.callback.sendComplete(
                            new PulsarClientException.ChecksumException("Checksum failded on corrupt message"));
                } catch (Throwable t) {
                    log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic,
                            producerName, sequenceId, t);
                }
                ReferenceCountUtil.safeRelease(op.cmd);
                op.recycle();
                return;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] [{}] Message is not corrupted, retry send-message with sequenceId {}",
                            topic, producerName, sequenceId);
                }
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] Corrupt message is already timed out {}", topic, producerName, sequenceId);
            }
        }
    }
    // as msg is not corrupted : let producer resend pending-messages again including checksum failed message
    resendMessages(cnx);
}

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

License:Apache License

/**
 * This fails and clears the pending messages with the given exception. This method should be called from within the
 * ProducerImpl object mutex.//  w  w w . j  a  va2s  .c om
 */
private void failPendingMessages(ClientCnx cnx, PulsarClientException ex) {
    if (cnx == null) {
        final AtomicInteger releaseCount = new AtomicInteger();
        pendingMessages.forEach(op -> {
            releaseCount.addAndGet(op.numMessagesInBatch);
            try {
                // Need to protect ourselves from any exception being thrown in the future handler from the
                // application
                op.callback.sendComplete(ex);
            } catch (Throwable t) {
                log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic,
                        producerName, op.sequenceId, t);
            }
            ReferenceCountUtil.safeRelease(op.cmd);
            op.recycle();
        });
        semaphore.release(releaseCount.get());
        pendingMessages.clear();
        pendingCallbacks.clear();
        if (isBatchMessagingEnabled()) {
            failPendingBatchMessages(ex);
        }
    } else {
        // If we have a connection, we schedule the callback and recycle on the event loop thread to avoid any
        // race condition since we also write the message on the socket from this thread
        cnx.ctx().channel().eventLoop().execute(() -> {
            synchronized (ProducerImpl.this) {
                failPendingMessages(null, ex);
            }
        });
    }
}

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

License:Apache License

/**
 * fail any pending batch messages that were enqueued, however batch was not closed out
 *
 *//*from   w ww  .j a  va  2s. co m*/
private void failPendingBatchMessages(PulsarClientException ex) {
    if (batchMessageContainer.isEmpty()) {
        return;
    }
    int numMessagesInBatch = batchMessageContainer.numMessagesInBatch;
    semaphore.release(numMessagesInBatch);
    try {
        // Need to protect ourselves from any exception being thrown in the future handler from the application
        batchMessageContainer.firstCallback.sendComplete(ex);
    } catch (Throwable t) {
        log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
                batchMessageContainer.sequenceId, t);
    }
    ReferenceCountUtil.safeRelease(batchMessageContainer.getBatchedSingleMessageMetadataAndPayload());
    batchMessageContainer.clear();
}

From source file:herddb.network.netty.ProtocolMessageDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*from ww  w .  ja  v a  2 s  .  com*/

    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, in);
        LOGGER.log(Level.FINEST, "Received from {}: {}", new Object[] { ctx.channel(), dumper });
    }

    try {
        Pdu pdu = PduCodec.decodePdu(in);
        ctx.fireChannelRead(pdu);
    } catch (Throwable err) {
        LOGGER.log(Level.SEVERE, "Error decoding PDU", err);
        ReferenceCountUtil.safeRelease(msg);
    }

}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@After
public void teardown() throws Exception {
    if (channel != null) {
        @SuppressWarnings("unused") // go/futurereturn-lsc
        Future<?> possiblyIgnoredError = channel.close();
    }/*  ww w.  j  a  v  a2  s .c  o  m*/

    for (ReferenceCounted reference : references) {
        ReferenceCountUtil.safeRelease(reference);
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {//  w ww .  j  av a2 s  .c  o m
        if (logger.isLoggable(Level.FINE)) {
            Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg;
            logger.log(Level.FINE, "Unexpected channelRead()->{0} reached end of pipeline {1}",
                    new Object[] { loggedMsg, ctx.pipeline().names() });
        }
        exceptionCaught(ctx,
                Status.INTERNAL.withDescription("channelRead() missed by ProtocolNegotiator handler: " + msg)
                        .asRuntimeException());
    } finally {
        ReferenceCountUtil.safeRelease(msg);
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

void onResponse(final DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope) {
    try {//from  w  w  w. j  ava2s .  co  m
        final DnsResponse res = envelope.content();
        final DnsResponseCode code = res.code();
        if (code == DnsResponseCode.NOERROR) {
            final DnsRecordType type = question.type();
            if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
                onResponseAorAAAA(type, question, envelope);
            } else if (type == DnsRecordType.CNAME) {
                onResponseCNAME(question, envelope);
            }
            return;
        }

        if (traceEnabled) {
            addTrace(envelope.sender(), "response code: " + code + " with " + res.count(DnsSection.ANSWER)
                    + " answer(s) and " + res.count(DnsSection.AUTHORITY) + " authority resource(s)");
        }

        // Retry with the next server if the server did not tell us that the domain does not exist.
        if (code != DnsResponseCode.NXDOMAIN) {
            query(nameServerAddrs.next(), question);
        }
    } finally {
        ReferenceCountUtil.safeRelease(envelope);
    }
}

From source file:io.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext)
        throws Exception {
    SslHandler sslHandler = null;//w  w w.j av a  2s .com
    try {
        SSLEngine engine = helper.createEngine(sslContext);
        sslHandler = new SslHandler(engine);
        ctx.pipeline().replace(this, "ssl", sslHandler);
        Future<Channel> fut = sslHandler.handshakeFuture();
        fut.addListener(future -> {
            if (future.isSuccess()) {
                Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
                val.set(hostname);
                handshakeFuture.setSuccess(ctx.channel());
            } else {
                handshakeFuture.setFailure(future.cause());
            }
        });
        sslHandler = null;
    } finally {
        // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
        // transferred to the SslHandler.
        // See https://github.com/netty/netty/issues/5678
        if (sslHandler != null) {
            ReferenceCountUtil.safeRelease(sslHandler.engine());
        }
    }
}

From source file:org.apache.bookkeeper.bookie.BufferedChannel.java

License:Apache License

@Override
public synchronized void close() throws IOException {
    if (closed) {
        return;/*www  .j av a 2s.c o m*/
    }
    ReferenceCountUtil.safeRelease(writeBuffer);
    fileChannel.close();
    closed = true;
}

From source file:org.apache.distributedlog.impl.logsegment.BKLogSegmentEntryReader.java

License:Apache License

private void readEntriesFromReadAheadCache(PendingReadRequest nextRequest) {
    while (!nextRequest.hasReadEnoughEntries()) {
        CacheEntry entry;/* w  ww  .j  a va 2s .  co m*/
        boolean hitEndOfLogSegment;
        synchronized (this) {
            entry = readAheadEntries.peek();
            hitEndOfLogSegment = (null == entry) && isEndOfLogSegment();
        }
        // reach end of log segment
        if (hitEndOfLogSegment) {
            completeExceptionally(new EndOfLogSegmentException(getSegment().getZNodeName()), false);
            return;
        }
        if (null == entry) {
            return;
        }
        // entry is not complete yet.
        if (!entry.isDone()) {
            // we already reached end of the log segment
            if (isEndOfLogSegment(entry.getEntryId())) {
                completeExceptionally(new EndOfLogSegmentException(getSegment().getZNodeName()), false);
            }
            return;
        }
        if (entry.isSuccess()) {
            CacheEntry removedEntry = readAheadEntries.poll();
            try {
                if (entry != removedEntry) {
                    DLIllegalStateException ise = new DLIllegalStateException(
                            "Unexpected condition at reading from " + getSegment());
                    completeExceptionally(ise, false);
                    return;
                }
                try {
                    // the reference is retained on `entry.getEntry()`.
                    // Entry.Reader is responsible for releasing it.
                    nextRequest.addEntry(processReadEntry(entry.getEntry()));
                } catch (IOException e) {
                    completeExceptionally(e, false);
                    return;
                }
            } finally {
                ReferenceCountUtil.safeRelease(removedEntry);
            }
        } else if (skipBrokenEntries && BKException.Code.DigestMatchException == entry.getRc()) {
            // skip this entry and move forward
            skippedBrokenEntriesCounter.inc();
            CacheEntry removedEntry = readAheadEntries.poll();
            removedEntry.release();
            continue;
        } else {
            completeExceptionally(new BKTransmitException("Encountered issue on reading entry "
                    + entry.getEntryId() + " @ log segment " + getSegment(), entry.getRc()), false);
            return;
        }
    }
}