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. Rails中关联数据表的添加操作(嵌套表单)

    很早就听说有Web敏捷开发这回事,最近终于闲了下来,可以利用业余的时间学些新东西,入眼的第一个东东自然是Ruby on Rails.Rails中的核心要素也就是MVC.ORM这些了,因此关于Rails ...

  2. Common webpart properties in kentico

    https://devnet.kentico.com/docs/7_0/devguide/index.html?common_web_part_properties.htm HTML Envelope ...

  3. Spring《三》ref 引用其他bean

    local属性 1.被引用id必须在同一个xml中. 2.被引用id必须使用id命名. 优点提前检查所使用的bean id是否正确. Bean属性 1.Bean指定的id可以在不同的xml中. 2.B ...

  4. Android 给WebView设置Cookie

    最近项目中用到WebView访问新浪支付页面,有个要求是必须是登录状态,否则会报Token过期,然后我简单的将我从cookie中取得的ticket,即一串数字可以代表用户登录的唯一标识作为参数拼接到u ...

  5. pgpool如何对数据库节点进行状态检查及相关数据结构描述

    /* * configuration parameters */typedef struct {    char *listen_addresses;            /* hostnames/ ...

  6. Unity中 Animator 与Animation 区别

    ①Animation和Animator 虽然都是控制动画的播放,但是它们的用法和相关语法都是大有不同的.Animation 控制一个动画的播放,而Animator是多个动画之间相互切换,并且Anima ...

  7. 第九章 Python之面向对象

    面向对象编程 面向对象编程是一种程序设计思想,它把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数 面向过程的程序设计把计算机程序视为一系列命令的集合,即一组函数的顺序执行.为了简化程序设计 ...

  8. DOS下格式化移动硬盘

    有的时候移动硬盘出现问题,在Win下没法操作,只能到dos下格式化.以下是用Win自带的diskpart完成格式化. 1  win + r   -> cmd  进入dos 2  diskpart ...

  9. 面试题sql

    查询书的价格10到20 之前显示10to20 没有显示unknown CREATE TABLE book(price INT,NAME VARCHAR(20)) SELECT NAME AS '名字' ...

  10. [分享]前端javascript插件(均开源)

    记录并分享一些自己使用过的插件,便于以后有相应的功能需要使用可以及时想到. 1:数字插件countUp.js 功能:用于动态显示数字的增加和减少 项目github地址:http://inorganik ...