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,如需转载请自行联系原作者


相关文章
|
6月前
|
缓存 网络协议 Dubbo
异步编程 - 12 异步、基于事件驱动的网络编程框架 Netty
异步编程 - 12 异步、基于事件驱动的网络编程框架 Netty
46 0
|
4月前
|
缓存 编解码 网络协议
一文带你由浅入深Netty异步非阻塞世界
一文带你由浅入深Netty异步非阻塞世界
一文带你由浅入深Netty异步非阻塞世界
|
2月前
|
前端开发 Java API
构建异步高并发服务器:Netty与Spring Boot的完美结合
构建异步高并发服务器:Netty与Spring Boot的完美结合
|
7月前
|
弹性计算 Java Unix
搭稳Netty开发的地基,用漫画帮你分清同步异步阻塞非阻塞
Netty Netty是一款非常优秀的网络编程框架,是对NIO的二次封装,本文将重点剖析Netty客户端的启动流程,深入底层了解如何使用NIO编程客户端。 Linux网络编程5种IO模型 根据UNIX网络编程对于IO模型的分类,UNIX提供了5种IO模型,分别是 阻塞IO 、 非阻塞IO、 IO复用 、 信号驱动IO 、 异步IO 。这几种IO模型在《UNIX网络编程》中有详解,这里作者只简单介绍,帮助大家回忆一下这几种模型。 对于Linux来说,所有的操作都是基于文件的,也就是我们非常熟悉的fd,在缺省的情况下,基于文件的操作都是 阻塞的 。下面就通过系统调用 recvfrom 来回顾下
63 0
|
3月前
Netty Review - 借助SimpleTalkRoom初体验异步网络编程的魅力
Netty Review - 借助SimpleTalkRoom初体验异步网络编程的魅力
39 0
|
9月前
|
前端开发 JavaScript
Netty异步NIO框架(二)websocket 前端后端聊天 私聊及群聊
Netty异步NIO框架(二)websocket 前端后端聊天 私聊及群聊
|
9月前
|
网络协议 前端开发 Java
Netty异步NIO框架(一)java服务端与客户端实现聊天 websocket通道
Netty异步NIO框架(一)java服务端与客户端实现聊天 websocket通道
|
Java Maven
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(二)
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(二)
455 0
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(二)
|
Java
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(一)
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(一)
233 0
【Netty】Netty 入门案例分析 ( Netty 线程模型 | Netty 案例需求 | IntelliJ IDEA 项目导入 Netty 开发库 )(一)
|
监控 前端开发 Java
netty案例,netty4.1源码分析篇六《Netty异步架构监听类Promise源码分析》
Netty是一个异步网络处理框架,在实现中大量使用了Future机制,并在Java自带Future的基础上,增加了Promise机制。这两个实现类的目的都是为了使异步编程更加方便使用。
251 0
netty案例,netty4.1源码分析篇六《Netty异步架构监听类Promise源码分析》