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:com.spotify.netty4.handler.codec.zmtp.CodecBenchmark.java

License:Apache License

@SuppressWarnings("ForLoopReplaceableByForEach")
private void consumeAndRelease(final Blackhole bh, final List<Object> out) {
    for (int i = 0; i < out.size(); i++) {
        final Object o = out.get(i);
        bh.consume(o);//from  w w  w. ja va 2 s  . c o  m
        ReferenceCountUtil.release(o);
    }
    out.clear();
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPFramingEncoder.java

License:Apache License

@Override
public void flush(final ChannelHandlerContext ctx) throws Exception {
    if (messages == null) {
        return;// ww w. jav  a2  s.  c  o  m
    }
    estimator.reset();
    for (final Object message : messages) {
        encoder.estimate(message, estimator);
    }
    final ByteBuf output = ctx.alloc().buffer(estimator.size());
    writer.reset(output);
    for (final Object message : messages) {
        encoder.encode(message, writer);
        ReferenceCountUtil.release(message);
    }
    final ChannelPromise aggregate = new AggregatePromise(ctx.channel(), promises);
    messages.clear();
    promises.clear();
    ctx.write(output, aggregate);
    ctx.flush();
}

From source file:com.superman.netty.handler.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {//  www. j av  a2  s  .co m
        ByteBuf bb = (ByteBuf) msg;
        while (bb.isReadable()) {
            System.out.print((char) bb.readByte());
            System.out.flush();
        }
    } finally {
        // ((ByteBuf) msg).release();
        ReferenceCountUtil.release(msg);
    }
    LOGGER.info("?");
}

From source file:com.tencent.mars.proxy.NetMsgHeaderHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {//  w  ww  .j  a  v a 2  s. c o  m
        // decode request
        final NetMsgHeader msgXp = new NetMsgHeader();
        final InputStream socketInput = new ByteBufInputStream((ByteBuf) msg);
        boolean ret = msgXp.decode(socketInput);
        IOUtils.closeQuietly(socketInput);

        if (!ret)
            return;

        linkTimeout.remove(ctx);
        linkTimeout.put(ctx, System.currentTimeMillis());
        logger.info(LogUtils.format("client req, cmdId=%d, seq=%d", msgXp.cmdId, msgXp.seq));

        final ProxySession proxySession = ProxySession.Manager.get(ctx);
        if (proxySession == null) {
        }

        String webCgi = CMD_PATH_MAP.get(msgXp.cmdId);
        switch (msgXp.cmdId) {
        case Main.CmdID.CMD_ID_HELLO_VALUE:
            InputStream requestDataStream = new ByteArrayInputStream(msgXp.body);
            InputStream inputStream = doHttpRequest(webCgi, requestDataStream);
            if (inputStream != null) {
                msgXp.body = IOUtils.toByteArray(inputStream);
                IOUtils.closeQuietly(requestDataStream);
                byte[] respBuf = msgXp.encode();
                logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId,
                        msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length));
                ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf));
            } else {

            }
            break;
        case Main.CmdID.CMD_ID_SEND_MESSAGE_VALUE:
            requestDataStream = new ByteArrayInputStream(msgXp.body);

            inputStream = doHttpRequest(webCgi, requestDataStream);
            if (inputStream != null) {
                msgXp.body = IOUtils.toByteArray(inputStream);
                Chat.SendMessageResponse response = Chat.SendMessageResponse.parseFrom(msgXp.body);
                if (response != null && response.getErrCode() == Chat.SendMessageResponse.Error.ERR_OK_VALUE) {
                    TopicChats.getInstance().pushMessage(response.getTopic(), response.getText(),
                            response.getFrom(), ctx);
                }
                IOUtils.closeQuietly(requestDataStream);
                byte[] respBuf = msgXp.encode();
                logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId,
                        msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length));
                ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf));
            } else {

            }
            break;
        case NetMsgHeader.CMDID_NOOPING:
            byte[] respBuf = msgXp.encode();
            logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq,
                    msgXp.body == null ? 0 : msgXp.body.length));
            ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf));
            break;
        default:
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.tesora.dve.db.mysql.libmy.MyFieldPktResponse.java

License:Open Source License

protected void updateCache(ByteBuf newCache) {
    ByteBuf oldCache = cachedBuffer;
    cachedBuffer = newCache;
    ReferenceCountUtil.release(oldCache);
}

From source file:com.tesora.dve.db.mysql.MysqlCommandSenderHandler.java

License:Open Source License

protected void dispatchRead(ChannelHandlerContext ctx, MyMessage message) throws Exception {
    boolean messageSignalsEndOfRequest = message.isSequenceEnd();
    boolean triggeredError = false;
    SimpleMysqlCommandBundle activeCommand = null;
    Timer responseProcessing = null;
    try {//from   w  ww . j  av  a  2s . c om

        activeCommand = activateFirstCommandIfNeeded(ctx);

        if (activeCommand == null) {
            logger.warn(String.format("Received message %s, but no active command registered, discarding.",
                    message.getClass().getName()));
            ReferenceCountUtil.release(message);
            return;
        }

        packetsInThisResponse++;

        if (logger.isDebugEnabled() && packetsInThisResponse == 1)
            logger.debug(ctx.channel() + ": results received for cmd " + activeCommand);

        responseProcessing = activeCommand.commandTimer.newSubTimer(TimingDesc.BACKEND_RESPONSE_PROCESSING);
        timingService.attachTimerOnThread(activeCommand.commandTimer);

        activeCommand.processPacket(ctx, message);

        responseProcessing.end(socketDesc, activeCommand.getClass().getName());

    } catch (PEException e) {
        triggeredError = true;
        activeCommand.failure(e);
    } catch (Exception e) {
        triggeredError = true;
        String errorMsg = String.format("encountered problem processing %s via %s, failing command.\n",
                (message.getClass().getName()),
                (activeCommand == null ? "null" : activeCommand.getClass().getName()));
        if (activeCommand == null || logger.isDebugEnabled())
            logger.warn(errorMsg, e);
        else
            logger.warn(errorMsg);
        if (activeCommand != null)
            activeCommand.failure(e);
    } finally {
        if (messageSignalsEndOfRequest) {
            popActiveCommand(ctx, triggeredError);
            activateFirstCommandIfNeeded(ctx);
        }
        timingService.detachTimerOnThread();
        if (responseProcessing != null)
            responseProcessing.end();
    }
}

From source file:com.tesora.dve.db.mysql.portal.MSPCommandHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof MSPMessage)) {
        ctx.fireChannelRead(msg); //not for us, maybe someone further in the stack can handle it.
        return;/*from   www .  j a va 2s.  c  om*/
    }

    final SSConnection ssCon = ctx.channel().attr(ConnectionHandlerAdapter.SSCON_KEY).get();
    try {

        //we start the timer here, outside the submit/callable, so that we include any delay in submission/execution around the thread pool.
        final Timer frontendRequest = timingService.startSubTimer(TimingDesc.FRONTEND_ROUND_TRIP);

        final MSPMessage mspMessage = (MSPMessage) msg;
        final byte theMessageType = mspMessage.getMysqlMessageType();

        clientExecutorService.submit(new Callable<Void>() {
            public Void call() throws Exception {
                ssCon.executeInContext(new Callable<Void>() {
                    public Void call() {
                        //bind the frontend timer to this thread, so that new sub-timers on this thread (planning, backend, etc ) will be children of the frontend request timer.
                        timingService.attachTimerOnThread(frontendRequest);
                        try {
                            MSPAction mspAction = instanceExecutor[theMessageType];
                            //TODO:need to get load data to play nice, this special casing violates the MSPAction abstraction and the copy/regex runs for every statement, even though 'load data' is uncommon. -sgossard
                            if (mspMessage instanceof MSPComQueryRequestMessage
                                    && (isLoadDataStmt((MSPComQueryRequestMessage) mspMessage))) {
                                MSPComQueryRequestMessage queryMessage = (MSPComQueryRequestMessage) mspMessage;
                                executeLoadDataStatement(clientExecutorService, ctx, ssCon, queryMessage);
                            } else {
                                mspAction.execute(clientExecutorService, ctx, ssCon, mspMessage);
                            }
                        } catch (Throwable t) {
                            ctx.fireExceptionCaught(t);
                        } finally {
                            ReferenceCountUtil.release(mspMessage);//we processed the message, so we are responsible for cleaning it up.
                            frontendRequest.end();
                            timingService.detachTimerOnThread();
                        }
                        return null;
                    }
                });
                return null;
            }
        });
    } finally {
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.CachedAppendBuffer.java

License:Open Source License

public void releaseSlab() {
    ReferenceCountUtil.release(cachedSlab);
    cachedSlab = null;
}

From source file:com.tesora.dve.db.mysql.portal.protocol.InboundMysqlAuthenticationHandlerV10.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    boolean forwarded = false;
    try {/* ww w .j ava 2 s  . com*/
        switch (currentAuthState) {
        case AUTHENTICATED:
            //already authenticated, pass decoded message through to other handler.
            forwarded = true;
            ctx.fireChannelRead(msg);
            break;
        case FAILED:
            ReferenceCountUtil.release(msg);
            ctx.channel().close();
            break;
        case UNAUTHENTICATED: {
            if (!(msg instanceof MSPAuthenticateV10MessageMessage))
                throw new PECodingException("Expecting authentication message, received, " + msg);

            MSPAuthenticateV10MessageMessage authMessage = (MSPAuthenticateV10MessageMessage) msg;
            authenticateClient(ctx, authMessage);
        }
            break;
        default:
            throw new PECodingException("Unexpected authorization state, " + currentAuthState);
        }
    } finally {
        if (!forwarded)
            ReferenceCountUtil.release(msg);
    }

}

From source file:com.tesora.dve.db.mysql.portal.protocol.Packet.java

License:Open Source License

public void release() {
    ReferenceCountUtil.release(header);
    ReferenceCountUtil.release(payload);
}