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
    }

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

  1. ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用!因此,ES transport client可以同步调用也可以异步(不过底层的socket必然是异步实现)

    ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用! 因此,ES tra ...

  2. twisted是python实现的基于事件驱动的异步网络通信构架。

    网:https://twistedmatrix.com/trac/ http://www.cnblogs.com/wy-wangyan/p/5252271.html What is Twisted? ...

  3. netty源码分析(十八)Netty底层架构系统总结与应用实践

    一个EventLoopGroup当中会包含一个或多个EventLoop. 一个EventLoop在它的整个生命周期当中都只会与唯一一个Thread进行绑定. 所有由EventLoop所处理的各种I/O ...

  4. python2.0_s12_day9_事件驱动编程&异步IO

    论事件驱动与异步IO 事件驱动编程是一种编程范式,这里程序的执行流由外部事件来决定.它的特点是包含一个事件循环,当外部事件发生时使用回调机制来触发相应的处理.另外两种常见的编程范式是(单线程)同步以及 ...

  5. 事件驱动与异步IO--待更新

    论事件驱动与异步IO 通常,我们写服务器处理模型的程序时,有以下几种模型: (1)每收到一个请求,创建一个新的进程,来处理该请求: (2)每收到一个请求,创建一个新的线程,来处理该请求: (3)每收到 ...

  6. python异步库

    https://github.com/aio-libs  异步库

  7. muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制

    目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...

  8. Netty源码分析第7章(编码器和写数据)---->第5节: Future和Promies

    Netty源码分析第七章: 编码器和写数据 第五节: Future和Promise Netty中的Future, 其实类似于jdk的Future, 用于异步获取执行结果 Promise则相当于一个被观 ...

  9. Oracle数据库由dataguard备库引起的log file sync等待

    导读: 最近数据库经常出现会话阻塞的报警,过一会又会自动消失,昨天晚上恰好发生了一次,于是赶紧进行了查看,不看不知道,一看吓一跳,发现是由dataguard引起的log file sync等待.我们知 ...

随机推荐

  1. 用shell脚本实现linux系统上wifi模式(STA和soft AP)的转换

    转载请注明出处:http://blog.csdn.net/hellomxj1/ 功能:在linux系统上实现wifi STA与AP功能的转换 实现成果:1.加入wifipassword账户add_wi ...

  2. 准确率99%!基于深度学习的二进制恶意样本检测——瀚思APT 沙箱恶意文件检测使用的是CNN,LSTM TODO

    所以我们的流程如图所示.将正负样本按 1:1 的比例转换为图像.将 ImageNet 中训练好的图像分类模型作为迁移学习的输入.在 GPU 集群中进行训练.我们同时训练了标准模型和压缩模型,对应不同的 ...

  3. numpy的scale就是 x-mean/std

    >>> from sklearn import preprocessing >>> import numpy as np >>> a=np.arr ...

  4. vue入门--初始化

    VUE初始化时,可以用vue init webpack-simple或者vue init webpack.前者是简易版的工程,后者是标准的初始化.工程创建成功后,打开发现两个的目录结构有很大不同.si ...

  5. Windows 10 的功能更新,版本 1809 - 错误 0x80070002

    一般是双硬盘导致的问题,请打开电脑拆掉系统盘以外的硬盘,一般为固态硬盘和物理硬盘同时使用的电脑会出现此错误.

  6. Python 之 PyCharm使用

    PyCharm  的官方网站地址是:https://www.jetbrains.com/pycharm/download/ 教育版:https://www.jetbrains.com/pycharm- ...

  7. js正则获取html字符串指定的dom元素和内容

    var str = "<div>111<p id='abc'>3333</p></div><div>222<div id=' ...

  8. ZBrush软件特性之Color调控板

    ZBrush®中的Color调色板显示当前颜色并提供数值的方法选择颜色,而且选择辅助色,使用描绘工具可以产生混合的色彩效果. ZBrush 4R8下载:http://wm.makeding.com/i ...

  9. 路飞学城Python-Day50

    05-运算符 常用运算符 算数运算符 赋值运算符 比较运算符 逻辑运算符         // 赋值运算符          var money = prompt('请输入金额');          ...

  10. ESM定义模块部分export用法

    //定义一个函数和变量 fonction myFunc(){}; const My_CONST=''; export {My_CONST AS THE_COMST,myFunc as THE_FUNC ...