netty底层是事件驱动的异步库 但是可以await或者sync(本质是future超时机制)同步返回 但是官方 Prefer addListener(GenericFutureListener) to await()
Interface ChannelFuture
- All Superinterfaces:
- java.util.concurrent.Future<java.lang.Void>
- All Known Subinterfaces:
- ChannelProgressiveFuture, ChannelProgressivePromise, ChannelPromise
- All Known Implementing Classes:
- DefaultChannelProgressivePromise, DefaultChannelPromise
public interface ChannelFuture
extends Future<java.lang.Void>The result of an asynchronousChannelI/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
ChannelFutureinstance which gives you the information about the result or status of the I/O operation.A
ChannelFutureis 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)toawait()It is recommended to prefer
addListener(GenericFutureListener)toawait()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 specifiedChannelFutureListenerto theChannelFuture, and I/O thread will notify the listeners when the I/O operation associated with the future is done.ChannelFutureListeneryields 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 withawait(), 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()insideChannelHandlerThe event handler methods in
ChannelHandlerare usually called by an I/O thread. Ifawait()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 becauseawait()can block the I/O operation it is waiting for, which is a dead lock.// BAD - NEVER DO THIS
@Override
public void channelRead(ChannelHandlerContextctx, Object msg) {
ChannelFuturefuture = ctx.channel().close();
future.awaitUninterruptibly();
// Perform post-closure operation
// ...
} // GOOD
@Override
public void channelRead(ChannelHandlerContextctx, Object msg) {
ChannelFuturefuture = ctx.channel().close();
future.addListener(newChannelFutureListener() {
public void operationComplete(ChannelFuturefuture) {
// 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 callawait()in an I/O thread. Otherwise,BlockingOperationExceptionwill 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), orFuture.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
Bootstrapb = ...;
ChannelFuturef = 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
Bootstrapb = ...;
// Configure the connect timeout option.
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
ChannelFuturef = 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()的更多相关文章
- ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用!因此,ES transport client可以同步调用也可以异步(不过底层的socket必然是异步实现)
ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用! 因此,ES tra ...
- twisted是python实现的基于事件驱动的异步网络通信构架。
网:https://twistedmatrix.com/trac/ http://www.cnblogs.com/wy-wangyan/p/5252271.html What is Twisted? ...
- netty源码分析(十八)Netty底层架构系统总结与应用实践
一个EventLoopGroup当中会包含一个或多个EventLoop. 一个EventLoop在它的整个生命周期当中都只会与唯一一个Thread进行绑定. 所有由EventLoop所处理的各种I/O ...
- python2.0_s12_day9_事件驱动编程&异步IO
论事件驱动与异步IO 事件驱动编程是一种编程范式,这里程序的执行流由外部事件来决定.它的特点是包含一个事件循环,当外部事件发生时使用回调机制来触发相应的处理.另外两种常见的编程范式是(单线程)同步以及 ...
- 事件驱动与异步IO--待更新
论事件驱动与异步IO 通常,我们写服务器处理模型的程序时,有以下几种模型: (1)每收到一个请求,创建一个新的进程,来处理该请求: (2)每收到一个请求,创建一个新的线程,来处理该请求: (3)每收到 ...
- python异步库
https://github.com/aio-libs 异步库
- muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制
目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...
- Netty源码分析第7章(编码器和写数据)---->第5节: Future和Promies
Netty源码分析第七章: 编码器和写数据 第五节: Future和Promise Netty中的Future, 其实类似于jdk的Future, 用于异步获取执行结果 Promise则相当于一个被观 ...
- Oracle数据库由dataguard备库引起的log file sync等待
导读: 最近数据库经常出现会话阻塞的报警,过一会又会自动消失,昨天晚上恰好发生了一次,于是赶紧进行了查看,不看不知道,一看吓一跳,发现是由dataguard引起的log file sync等待.我们知 ...
随机推荐
- TNS-12555 / TNS-12560 / TNS-00525 Error listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPR
TNS-12555 / TNS-12560 / TNS-00525 Error listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPR ...
- 基于macOS+VMware的GNS3内VM上公网
笔者经常需要做网络实验,GNS3就是笔者最喜欢用的模拟器,为了便于实验,需要能从macos上直接ssh登陆模拟出来的vm,并且vm需要上公网.经过研究,已解决此问题,并以此分享出来 tag: maco ...
- Response.Redirect(),Server.Transfer(),Server.Execute()的区别与网站优化
转 http://blog.csdn.net/dannywj1371/article/details/10213631 1.Response.Redirect():Response.Redirect方 ...
- 关于swift构造方法
switf 中如果遇到这样的错,,,大概错误就是,"必须要调用父类的构造方法",,可是呢,,调用了super.init() 不就是调用了构造方法了吗? 结果上去一查,,结果一名外 ...
- 阿里云Maven中央仓库配置
方式一:统一配置 在maven安装目录/conf下的settings.xml 文件里配置mirrors的子节点,添加如下mirror <mirror> <id>alimaven ...
- Python学习——爬虫篇
requests 使用requests进行爬取 下面是我编写的第一个爬虫的脚本 import requests # 导入reques ...
- Thinkphp开源框架如何使用?
(一)首先是准备工作下载thinkPHP框架最新版本,解压缩到你将要开发的项目位置.杭州php操作演示如图: 其中index.php是入口文件,即所有的请求都要经过此文件才能够完成.Applicati ...
- fiddler一些高级用法
https://my.oschina.net/leejun2005/blog/399108
- MAC 下的pycharm部分使用方法
1.在创建之初,可以选择自己想要使用的python版本. 如果之后想要更换Python版本,可以通过~~~更换选择Python版本. 2.创建.py文件,点击文件名,出现如下界面: 点击new--py ...
- Pyhton学习——Day28
#上下文协议:文件操作时使用with执行# with open('a.txt','w',encoding='utf-8') as f1:# with语句,为了让一个对象兼容with语句,必须在这个对象 ...