netty底层是事件驱动的异步库 但是可以await或者sync(本质是future超时机制)同步返回 但是官方 Prefer addListener(GenericFutureListener) to await()

简介:
io.netty.channel
摘自:https://netty.io/4.0/api/io/netty/channel/ChannelFuture.html

Interface ChannelFuture

  • All Superinterfaces:
    java.util.concurrent.Future<java.lang.Void>
    All Known Subinterfaces:
    ChannelProgressiveFutureChannelProgressivePromiseChannelPromise
    All Known Implementing Classes:
    DefaultChannelProgressivePromiseDefaultChannelPromise


    public interface ChannelFuture
    extends Future<java.lang.Void>
    The result of an asynchronous  Channel I/O operation.

    All I/O operations in Netty are asynchronous. It means any I/O calls will return immediately with no guarantee that the requested I/O operation has been completed at the end of the call. Instead, you will be returned with a ChannelFuture instance which gives you the information about the result or status of the I/O operation.

    ChannelFuture is either uncompleted or completed. When an I/O operation begins, a new future object is created. The new future is uncompleted initially - it is neither succeeded, failed, nor cancelled because the I/O operation is not finished yet. If the I/O operation is finished either successfully, with failure, or by cancellation, the future is marked as completed with more specific information, such as the cause of the failure. Please note that even failure and cancellation belong to the completed state.

                                          +---------------------------+
                                          | Completed successfully    |
                                          +---------------------------+
                                     +---->      isDone() = true      |
     +--------------------------+    |    |   isSuccess() = true      |
     |        Uncompleted       |    |    +===========================+
     +--------------------------+    |    | Completed with failure    |
     |      isDone() = false    |    |    +---------------------------+
     |   isSuccess() = false    |----+---->      isDone() = true      |
     | isCancelled() = false    |    |    |       cause() = non-null  |
     |       cause() = null     |    |    +===========================+
     +--------------------------+    |    | Completed by cancellation |
                                     |    +---------------------------+
                                     +---->      isDone() = true      |
                                          | isCancelled() = true      |
                                          +---------------------------+
     
    Various methods are provided to let you check if the I/O operation has been completed, wait for the completion, and retrieve the result of the I/O operation. It also allows you to add  ChannelFutureListeners so you can get notified when the I/O operation is completed.

    Prefer addListener(GenericFutureListener) to await()

    It is recommended to prefer  addListener(GenericFutureListener) to  await() wherever possible to get notified when an I/O operation is done and to do any follow-up tasks.

    addListener(GenericFutureListener) is non-blocking. It simply adds the specified ChannelFutureListener to the ChannelFuture, and I/O thread will notify the listeners when the I/O operation associated with the future is done. ChannelFutureListener yields the best performance and resource utilization because it does not block at all, but it could be tricky to implement a sequential logic if you are not used to event-driven programming.

    By contrast, await() is a blocking operation. Once called, the caller thread blocks until the operation is done. It is easier to implement a sequential logic with await(), but the caller thread blocks unnecessarily until the I/O operation is done and there's relatively expensive cost of inter-thread notification. Moreover, there's a chance of dead lock in a particular circumstance, which is described below.

    Do not call await() inside ChannelHandler

    The event handler methods in ChannelHandler are usually called by an I/O thread. If await() is called by an event handler method, which is called by the I/O thread, the I/O operation it is waiting for might never complete because await() can block the I/O operation it is waiting for, which is a dead lock.

     // BAD - NEVER DO THIS
      @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) {
         ChannelFuture future = ctx.channel().close();
         future.awaitUninterruptibly();
         // Perform post-closure operation
         // ...
     }
    
     // GOOD
      @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) {
         ChannelFuture future = ctx.channel().close();
         future.addListener(new ChannelFutureListener() {
             public void operationComplete(ChannelFuture future) {
                 // Perform post-closure operation
                 // ...
             }
         });
     }
     

    In spite of the disadvantages mentioned above, there are certainly the cases where it is more convenient to call await(). In such a case, please make sure you do not call await() in an I/O thread. Otherwise, BlockingOperationException will be raised to prevent a dead lock.

    Do not confuse I/O timeout and await timeout

    The timeout value you specify with  Future.await(long)Future.await(long, TimeUnit)Future.awaitUninterruptibly(long), or  Future.awaitUninterruptibly(long, TimeUnit) are not related with I/O timeout at all. If an I/O operation times out, the future will be marked as 'completed with failure,' as depicted in the diagram above. For example, connect timeout should be configured via a transport-specific option:
     // BAD - NEVER DO THIS
     Bootstrap b = ...;
     ChannelFuture f = b.connect(...);
     f.awaitUninterruptibly(10, TimeUnit.SECONDS);
     if (f.isCancelled()) {
         // Connection attempt cancelled by user
     } else if (!f.isSuccess()) {
         // You might get a NullPointerException here because the future
         // might not be completed yet.
         f.cause().printStackTrace();
     } else {
         // Connection established successfully
     }
    
     // GOOD
     Bootstrap b = ...;
     // Configure the connect timeout option.
     b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
     ChannelFuture f = b.connect(...);
     f.awaitUninterruptibly();
    
     // Now we are sure the future is completed.
     assert f.isDone();
    
     if (f.isCancelled()) {
         // Connection attempt cancelled by user
     } else if (!f.isSuccess()) {
         f.cause().printStackTrace();
     } else {
         // Connection established successfully
     }
     













本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/7889876.html,如需转载请自行联系原作者


相关文章
|
监控 网络协议 Java
Java一分钟之-Netty:高性能异步网络库
【6月更文挑战第11天】Netty是Java的高性能异步网络框架,基于NIO,以其高吞吐量、低延迟、灵活性和安全性受到青睐。常见问题包括内存泄漏、ChannelHandler滥用和异常处理不当。要规避这些问题,需正确释放ByteBuf,精简ChannelPipeline,妥善处理异常,并深入理解Netty原理。通过代码审查、遵循最佳实践和监控日志,可提升代码质量和性能。掌握Netty,打造高效网络服务。
233 2
|
安全 NoSQL Java
网络安全-----Redis12的Java客户端----客户端对比12,Jedis介绍,使用简单安全性不足,lettuce(官方默认)是基于Netty,支持同步,异步和响应式,并且线程是安全的,支持R
网络安全-----Redis12的Java客户端----客户端对比12,Jedis介绍,使用简单安全性不足,lettuce(官方默认)是基于Netty,支持同步,异步和响应式,并且线程是安全的,支持R
|
存储 缓存 运维
时间轮奇妙旅程:深度解析Netty中的时间轮机制
时间轮奇妙旅程:深度解析Netty中的时间轮机制
585 1
|
前端开发 网络协议
启动异步之旅:探索Netty中Bootstrap的神奇世界
启动异步之旅:探索Netty中Bootstrap的神奇世界
126 0
|
前端开发 网络协议 Java
Netty入门指南:从零开始的异步网络通信
Netty入门指南:从零开始的异步网络通信
360 0
|
存储 缓存 NoSQL
跟着源码学IM(十一):一套基于Netty的分布式高可用IM详细设计与实现(有源码)
本文将要分享的是如何从零实现一套基于Netty框架的分布式高可用IM系统,它将支持长连接网关管理、单聊、群聊、聊天记录查询、离线消息存储、消息推送、心跳、分布式唯一ID、红包、消息同步等功能,并且还支持集群部署。
13848 1
|
7月前
|
算法 Java 容器
Netty源码—4.客户端接入流程
本文主要介绍了关于Netty客户端连接接入问题整理、Reactor线程模型和服务端启动流程、Netty新连接接入的整体处理逻辑、新连接接入之检测新连接、新连接接入之创建NioSocketChannel、新连接接入之绑定NioEventLoop线程、新连接接入之注册Selector和注册读事件、注册Reactor线程总结、新连接接入总结
|
7月前
|
安全 Java 调度
Netty源码—3.Reactor线程模型二
本文主要介绍了NioEventLoop的执行总体框架、Reactor线程执行一次事件轮询、Reactor线程处理产生IO事件的Channel、Reactor线程处理任务队列之添加任务、Reactor线程处理任务队列之执行任务、NioEventLoop总结。
|
7月前
|
安全 Java
Netty源码—2.Reactor线程模型一
本文主要介绍了关于NioEventLoop的问题整理、理解Reactor线程模型主要分三部分、NioEventLoop的创建和NioEventLoop的启动。
|
7月前
|
编解码 安全 Java
Netty源码—1.服务端启动流程
本文主要介绍了服务端启动整体流程及关键方法、服务端启动的核心步骤、创建服务端Channel的源码、初始化服务端Channel的源码、注册服务端Channel的源码、绑定服务端端口的源码、服务端启动流程源码总结。