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. springmvc+spring+jpa(hibernate)+redis+maven配置

    废话不多少 项目结构 pom.xml配置例如以下 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=& ...

  2. javascript系列-class12.事件

    1.默认行为          什么是默认行为:默认行为就是浏览器自己触发的事件.比如:a链接的跳转,form提交时的跳转,鼠标右键跳转:   oncontexmenu当点击右键菜单的时候:   re ...

  3. BZOJ 2120 带修莫队

    思路: 暴力能过的 嘿嘿嘿 我是来练带修莫队的嗯 复杂度 O(n^5/3) //By SiriusRen #include <cmath> #include <cstdio> ...

  4. C++中static和const关键字的作用

    static关键字至少有下列几个作用: 函数体内static变量的作用范围为该函数体,不同于auto变量,该变量的内存只被分配一次,因此其值在下次调用时仍维持上次的值: 在模块内的static全局变量 ...

  5. Dynamic programming language

    动态改变运行时结构 Dynamic programming language, in computer science, is a class of high-level programming la ...

  6. unity 模型 材质 贴图 关系;着色器属性

    模型包含 材质(Material),包括 [核心]着色器(Shader) 贴图和其他参数,贴图也算是一种参数 其他,如网格渲染器(Mesh Renderer).动画.坐标 一个材质可以看做为一个Sha ...

  7. LeetCode Golang 9.回文数

    9. 回文数 第一种办法 :itoa 转换为字符串进行处理: package main import ( "strconv" "fmt" ) //判断一个整数是 ...

  8. Prime Distance POJ - 2689 线性筛

    一个数 $n$ 必有一个不超过 $\sqrt n$ 的质因子. 打表处理出 $1$ 到 $\sqrt n$ 的质因子后去筛掉属于 $L$ 到 $R$ 区间的素数即可. Code: #include&l ...

  9. [实验楼]python11期--NO.1(未完成)

    tuple 是 Python 的一种不可变数据类型,用于列表数据一旦初始化就不会再修改的场景.tuple 只能通过位置索引去访问里面的元素,但有时候我们需要给每个元素取个别名,以便通过别名去获取对应的 ...

  10. Pyhton学习——Day25

    #面向对象的几个方法#1.静态方法@staticmethod,不能访问类属性,也不能访问实例属性,只是类的工具包#2.类方法:@classmethod,在函数属性前加上类方法,显示为(cls)代表类, ...