try catch finally中finally代码块有主线程执行?

Posted 技术无产者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了try catch finally中finally代码块有主线程执行?相关的知识,希望对你有一定的参考价值。

public static void init(){
        NioEventLoopGroup group=new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER=new LoggingHandler(LogLevel.DEBUG);
        MessageCodecProtocol MESSAGE_CODEC=new MessageCodecProtocol();
        MessageDuplexHandler DUPLEX_HANDLER=new MessageDuplexHandler();
        RpcResponseHandler RESPONSE_HANDLER=new RpcResponseHandler();
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.channel(NiosocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new FrameDecoderProtocol());
                ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                ch.pipeline().addLast(new IdleStateHandler(0,10,0, TimeUnit.SECONDS));
                ch.pipeline().addLast(DUPLEX_HANDLER);
                ch.pipeline().addLast(RESPONSE_HANDLER);
                }
            });
            channel = bootstrap.connect(host, port).sync().channel();
            channel.closeFuture()
                    .addListener((promise)->{
                    log.info("***remoting service close");
                        System.out.println("222222222");
            });
        } catch (InterruptedException e) {
            log.error("***remoting service exception:[{}]",e.getCause().getMessage());
        } finally {
            log.error("****************");
            System.out.println("111111111");
            group.shutdownGracefully();
        }
    }

res: 结果可以看出来 finally在辅助线程还没执行完的时候就执行Finally代码块的内容了,所以在异步
时注意资源的释放位置

09:34:43.705 [main] ERROR com.fastrpc.remoting.netty.client.NettyRpcClient - ****************
111111111
09:34:43.706 [nioEventLoopGroup-2-1] INFO com.fastrpc.remoting.netty.client.NettyRpcClient - ***remoting service close
222222222

以上是关于try catch finally中finally代码块有主线程执行?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在 Try ... Catch 中使用 finally

try{ } catch{ } finally{ }

try catch finally

对try catch finally的理解

java之try catch finally

为啥 try..catch..finally 块的 finally 节在 catch 之前运行?