Example usage for io.netty.util ReferenceCountUtil release

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

Introduction

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

Prototype

public static boolean release(Object msg) 

Source Link

Document

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

Usage

From source file:org.apache.bookkeeper.proto.ReadEntryProcessorV3.java

License:Apache License

/**
 * Read a specific entry.//from w  ww . ja v  a 2 s  . c o m
 *
 * @param readResponseBuilder
 *          read response builder.
 * @param entryId
 *          entry to read
 * @param startTimeSw
 *          stop watch to measure the read operation.
 * @return read response or null if it is a fence read operation.
 * @throws IOException
 */
protected ReadResponse readEntry(ReadResponse.Builder readResponseBuilder, long entryId,
        boolean readLACPiggyBack, Stopwatch startTimeSw) throws IOException {
    ByteBuf entryBody = requestProcessor.getBookie().readEntry(ledgerId, entryId);
    if (null != fenceResult) {
        handleReadResultForFenceRead(entryBody, readResponseBuilder, entryId, startTimeSw);
        return null;
    } else {
        try {
            readResponseBuilder.setBody(ByteString.copyFrom(entryBody.nioBuffer()));
            if (readLACPiggyBack) {
                readResponseBuilder.setEntryId(entryId);
            } else {
                long knownLAC = requestProcessor.getBookie().readLastAddConfirmed(ledgerId);
                readResponseBuilder.setMaxLAC(knownLAC);
            }
            registerSuccessfulEvent(readStats, startTimeSw);
            readResponseBuilder.setStatus(StatusCode.EOK);
            return readResponseBuilder.build();
        } finally {
            ReferenceCountUtil.release(entryBody);
        }
    }
}

From source file:org.apache.bookkeeper.proto.ReadEntryProcessorV3.java

License:Apache License

private void getFenceResponse(ReadResponse.Builder readResponse, ByteBuf entryBody, boolean fenceResult) {
    StatusCode status;/*w w  w  .jav  a  2s  .co  m*/
    if (!fenceResult) {
        status = StatusCode.EIO;
        registerFailedEvent(requestProcessor.getRequestStats().getFenceReadWaitStats(), lastPhaseStartTime);
    } else {
        status = StatusCode.EOK;
        readResponse.setBody(ByteString.copyFrom(entryBody.nioBuffer()));
        registerSuccessfulEvent(requestProcessor.getRequestStats().getFenceReadWaitStats(), lastPhaseStartTime);
    }

    if (null != entryBody) {
        ReferenceCountUtil.release(entryBody);
    }

    readResponse.setStatus(status);
}

From source file:org.apache.bookkeeper.proto.ReadLacProcessorV3.java

License:Apache License

private ReadLacResponse getReadLacResponse() {
    final long startTimeNanos = MathUtils.nowInNano();
    ReadLacRequest readLacRequest = request.getReadLacRequest();
    long ledgerId = readLacRequest.getLedgerId();

    final ReadLacResponse.Builder readLacResponse = ReadLacResponse.newBuilder().setLedgerId(ledgerId);

    if (!isVersionCompatible()) {
        readLacResponse.setStatus(StatusCode.EBADVERSION);
        return readLacResponse.build();
    }/*from  ww  w.  j a  va 2  s  . c om*/

    logger.debug("Received ReadLac request: {}", request);
    StatusCode status = StatusCode.EOK;
    ByteBuf lastEntry = null;
    ByteBuf lac = null;
    try {
        lac = requestProcessor.bookie.getExplicitLac(ledgerId);
        if (lac != null) {
            readLacResponse.setLacBody(ByteString.copyFrom(lac.nioBuffer()));
        }
    } catch (Bookie.NoLedgerException e) {
        status = StatusCode.ENOLEDGER;
        logger.error("No ledger found while performing readLac from ledger: {}", ledgerId, e);
    } catch (IOException e) {
        status = StatusCode.EIO;
        logger.error("IOException while performing readLac from ledger: {}", ledgerId);
    } finally {
        ReferenceCountUtil.release(lac);
    }

    try {
        lastEntry = requestProcessor.bookie.readEntry(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED);
        if (lastEntry != null) {
            readLacResponse.setLastEntryBody(ByteString.copyFrom(lastEntry.nioBuffer()));
        }
    } catch (Bookie.NoLedgerException e) {
        status = StatusCode.ENOLEDGER;
        logger.error("No ledger found while trying to read last entry: {}", ledgerId, e);
    } catch (IOException e) {
        status = StatusCode.EIO;
        logger.error("IOException while trying to read last entry: {}", ledgerId, e);
    } finally {
        ReferenceCountUtil.release(lastEntry);
    }

    if ((lac == null) && (lastEntry == null)) {
        status = StatusCode.ENOENTRY;
    }

    if (status == StatusCode.EOK) {
        requestProcessor.getRequestStats().getReadLacStats()
                .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS);
    } else {
        requestProcessor.getRequestStats().getReadLacStats()
                .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS);
    }
    // Finally set the status and return
    readLacResponse.setStatus(status);
    return readLacResponse.build();
}

From source file:org.apache.distributedlog.EnvelopedEntryWriter.java

License:Apache License

@Override
public void completeTransmit(long lssn, long entryId) {
    satisfyPromises(lssn, entryId);/*w  w w  . j  a v a 2s  .co  m*/
    buffer.release();
    synchronized (this) {
        ReferenceCountUtil.release(finalizedBuffer);
    }
}

From source file:org.apache.distributedlog.EnvelopedEntryWriter.java

License:Apache License

@Override
public void abortTransmit(Throwable reason) {
    cancelPromises(reason);/*from  www .  j  a  v  a  2s .co  m*/
    buffer.release();
    synchronized (this) {
        ReferenceCountUtil.release(finalizedBuffer);
    }
}

From source file:org.apache.distributedlog.EnvelopedRecordSetWriter.java

License:Apache License

@Override
public synchronized void completeTransmit(long lssn, long entryId, long startSlotId) {
    satisfyPromises(lssn, entryId, startSlotId);
    buffer.release();//from   w w  w  .  j a va  2s  .  c  o  m
    ReferenceCountUtil.release(recordSetBuffer);
}

From source file:org.apache.distributedlog.EnvelopedRecordSetWriter.java

License:Apache License

@Override
public synchronized void abortTransmit(Throwable reason) {
    cancelPromises(reason);
    buffer.release();
    ReferenceCountUtil.release(recordSetBuffer);
}

From source file:org.apache.flink.runtime.query.netty.KvStateClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {//  www .  j ava 2s  .  c  o m
        ByteBuf buf = (ByteBuf) msg;
        KvStateRequestType msgType = KvStateRequestSerializer.deserializeHeader(buf);

        if (msgType == KvStateRequestType.REQUEST_RESULT) {
            KvStateRequestResult result = KvStateRequestSerializer.deserializeKvStateRequestResult(buf);
            callback.onRequestResult(result.getRequestId(), result.getSerializedResult());
        } else if (msgType == KvStateRequestType.REQUEST_FAILURE) {
            KvStateRequestFailure failure = KvStateRequestSerializer.deserializeKvStateRequestFailure(buf);
            callback.onRequestFailure(failure.getRequestId(), failure.getCause());
        } else if (msgType == KvStateRequestType.SERVER_FAILURE) {
            throw KvStateRequestSerializer.deserializeServerFailure(buf);
        } else {
            throw new IllegalStateException("Unexpected response type '" + msgType + "'");
        }
    } catch (Throwable t1) {
        try {
            callback.onFailure(t1);
        } catch (Throwable t2) {
            LOG.error("Failed to notify callback about failure", t2);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.apache.flink.runtime.query.netty.KvStateServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    KvStateRequest request = null;/*from w  w w .ja v  a 2s.  c  o m*/

    try {
        ByteBuf buf = (ByteBuf) msg;
        KvStateRequestType msgType = KvStateRequestSerializer.deserializeHeader(buf);

        if (msgType == KvStateRequestType.REQUEST) {
            // ------------------------------------------------------------
            // Request
            // ------------------------------------------------------------
            request = KvStateRequestSerializer.deserializeKvStateRequest(buf);

            stats.reportRequest();

            InternalKvState<?> kvState = registry.getKvState(request.getKvStateId());

            if (kvState != null) {
                // Execute actual query async, because it is possibly
                // blocking (e.g. file I/O).
                //
                // A submission failure is not treated as fatal.
                queryExecutor.submit(new AsyncKvStateQueryTask(ctx, request, kvState, stats));
            } else {
                ByteBuf unknown = KvStateRequestSerializer.serializeKvStateRequestFailure(ctx.alloc(),
                        request.getRequestId(), new UnknownKvStateID(request.getKvStateId()));

                ctx.writeAndFlush(unknown);

                stats.reportFailedRequest();
            }
        } else {
            // ------------------------------------------------------------
            // Unexpected
            // ------------------------------------------------------------
            ByteBuf failure = KvStateRequestSerializer.serializeServerFailure(ctx.alloc(),
                    new IllegalArgumentException("Unexpected message type " + msgType
                            + ". KvStateServerHandler expects " + KvStateRequestType.REQUEST + " messages."));

            ctx.writeAndFlush(failure);
        }
    } catch (Throwable t) {
        String stringifiedCause = ExceptionUtils.stringifyException(t);

        ByteBuf err;
        if (request != null) {
            String errMsg = "Failed to handle incoming request with ID " + request.getRequestId()
                    + ". Caused by: " + stringifiedCause;
            err = KvStateRequestSerializer.serializeKvStateRequestFailure(ctx.alloc(), request.getRequestId(),
                    new RuntimeException(errMsg));

            stats.reportFailedRequest();
        } else {
            String errMsg = "Failed to handle incoming message. Caused by: " + stringifiedCause;
            err = KvStateRequestSerializer.serializeServerFailure(ctx.alloc(), new RuntimeException(errMsg));
        }

        ctx.writeAndFlush(err);
    } finally {
        // IMPORTANT: We have to always recycle the incoming buffer.
        // Otherwise we will leak memory out of Netty's buffer pool.
        //
        // If any operation ever holds on to the buffer, it is the
        // responsibility of that operation to retain the buffer and
        // release it later.
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.apache.giraph.comm.netty.handler.RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof ByteBuf)) {
        throw new IllegalStateException("decode: Got illegal message " + msg);
    }//from w  w  w. j a  v a  2s  . co  m
    // Output metrics every 1/2 minute
    String metrics = byteCounter.getMetricsWindow(30000);
    if (metrics != null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("decode: Server window metrics " + metrics);
        }
    }

    if (LOG.isDebugEnabled()) {
        startDecodingNanoseconds = TIME.getNanoseconds();
    }

    // Decode the request
    ByteBuf buf = (ByteBuf) msg;
    int enumValue = buf.readByte();
    RequestType type = RequestType.values()[enumValue];
    Class<? extends WritableRequest> requestClass = type.getRequestClass();
    WritableRequest request = ReflectionUtils.newInstance(requestClass, conf);
    request = RequestUtils.decodeWritableRequest(buf, request);

    if (LOG.isDebugEnabled()) {
        LOG.debug("decode: Client " + request.getClientId() + ", requestId " + request.getRequestId() + ", "
                + request.getType() + ", with size " + buf.writerIndex() + " took "
                + Times.getNanosSince(TIME, startDecodingNanoseconds) + " ns");
    }
    ReferenceCountUtil.release(buf);
    // fire writableRequest object to upstream handlers
    ctx.fireChannelRead(request);
}