Netty中的Future
先看下Future的整个继承体系,还有一个ChannelFuture不在里面;

- Future<V>的V为异步结果的返回类型
- getNow 是无阻塞调用,返回异步执行结果,如果未完成那么返回null
- await 是阻塞调用,等到异步执行完成
- isSuccess 执行成功是否成功
- sync 阻塞调用,等待这个future直到isDone(可能由于正常终止、异常或取消而完成)返回true; 如果该future失败,重新抛出失败的原因。 和await区别就是返回结果不同,它返回一个Future对象,通过这个Future知道任务执行结果。
- 添加GenericFutureListener, 执行完成(future可能由于正常终止、异常或取消而完成)后调用该监听器。
privatefinalEventExecutor executor; //任务执行器
privatevolatileObject result;//不仅仅是结果,也有可能是异常
* 一个或多个监听器,可能是GenericFutureListener或者DefaultFutureListeners。如果是NULL有两种可能
* 1:没有添加触发器
* 2:已经出发了privateObject listeners;
privateLateListeners lateListeners;
privateshort waiters;
privatestaticboolean isDone0(Object result){
return result !=null&& result != UNCANCELLABLE;
}
publicboolean isSuccess(){
Object result =this.result;
if(result ==null|| result == UNCANCELLABLE){
returnfalse;
}
return!(result instanceofCauseHolder);
}
public V getNow(){
Object result =this.result;
if(result instanceofCauseHolder|| result == SUCCESS){
returnnull;
}
return(V) result;
}
@Override
publicPromise<V> sync()throwsInterruptedException{
await();
rethrowIfFailed();
returnthis;
}
@Override
publicPromise<V> await()throwsInterruptedException{
if(isDone()){
returnthis;
}
if(Thread.interrupted()){
thrownewInterruptedException(toString());
}
synchronized(this){
while(!isDone()){
checkDeadLock();//判断当前线程是否是执行线程。如果是抛出异常。
incWaiters();//添加等待个数
try{
wait();//释放锁,等待唤醒,阻塞该线程
}finally{
decWaiters();
}
}
}
returnthis;
}
@Override
publicboolean cancel(boolean mayInterruptIfRunning){
Object result =this.result;
if(isDone0(result)|| result == UNCANCELLABLE){
returnfalse;
}
synchronized(this){
// Allow only once.
result =this.result;
if(isDone0(result)|| result == UNCANCELLABLE){
returnfalse;
}
this.result = CANCELLATION_CAUSE_HOLDER;
if(hasWaiters()){
notifyAll();
}
}
notifyListeners();
returntrue;
}
/**
* 该方法不需要异步,为啥呢
* 1:这个方法在同步代码块里面调用,因此任何监听器列表的改变都happens-before该方法
* 2:该方法只有isDone==true的时候调用,一但 isDone==true 那么监听器列表将不会改变
*/
privatevoid notifyListeners(){
Object listeners =this.listeners;
if(listeners ==null){
return;
}
EventExecutor executor = executor();
if(executor.inEventLoop()){
finalInternalThreadLocalMap threadLocals =InternalThreadLocalMap.get();
finalint stackDepth = threadLocals.futureListenerStackDepth();
if(stackDepth < MAX_LISTENER_STACK_DEPTH){
threadLocals.setFutureListenerStackDepth(stackDepth +1);
try{
if(listeners instanceofDefaultFutureListeners){
notifyListeners0(this,(DefaultFutureListeners) listeners);
}else{
finalGenericFutureListener<?extendsFuture<V>> l =
(GenericFutureListener<?extendsFuture<V>>) listeners;
notifyListener0(this, l);
}
}finally{
this.listeners =null;
threadLocals.setFutureListenerStackDepth(stackDepth);
}
return;
}
}
if(listeners instanceofDefaultFutureListeners){
finalDefaultFutureListeners dfl =(DefaultFutureListeners) listeners;
execute(executor,newRunnable(){
@Override
publicvoid run(){
notifyListeners0(DefaultPromise.this, dfl);
DefaultPromise.this.listeners =null;
}
});
}else{
finalGenericFutureListener<?extendsFuture<V>> l =
(GenericFutureListener<?extendsFuture<V>>) listeners;
execute(executor,newRunnable(){
@Override
publicvoid run(){
notifyListener0(DefaultPromise.this, l);
DefaultPromise.this.listeners =null;
}
});
}
}
@Override
publicboolean setUncancellable(){
Object result =this.result;
if(isDone0(result)){
return!isCancelled0(result);
}
synchronized(this){
// Allow only once.
result =this.result;
if(isDone0(result)){
return!isCancelled0(result);
}
this.result = UNCANCELLABLE;
}
returntrue;
}
privateboolean setFailure0(Throwable cause){
if(cause ==null){
thrownewNullPointerException("cause");
}
if(isDone()){
returnfalse;
}
synchronized(this){
// Allow only once.
if(isDone()){
returnfalse;
}
result =newCauseHolder(cause);
if(hasWaiters()){
notifyAll();
}
}
returntrue;
}
privateboolean setSuccess0(V result){
if(isDone()){
returnfalse;
}
synchronized(this){
// Allow only once.
if(isDone()){
returnfalse;
}
if(result ==null){
this.result = SUCCESS;
}else{
this.result = result;
}
if(hasWaiters()){
notifyAll();
}
}
returntrue;
}
CompleteFuture的几个子类是状态Promise
PromiseTask:该类继承了RunnableFuture接口,该类表示异步操作的结果也可以异步获得,类似JDK中的FutureTask,实例化该对象时候需要传一个Callable的对象,如果没有该对象可以传递一个Runnable和一个Result构造一个Callable对象。
privatestaticfinalclassRunnableAdapter<T>implementsCallable<T>{
finalRunnable task;
final T result;
RunnableAdapter(Runnable task, T result){
this.task = task;
this.result = result;
}
@Override
public T call(){
task.run();
return result;
}
@Override
publicString toString(){
return"Callable(task: "+ task +", result: "+ result +')';
}
}
@Override
publicvoid run(){
try{
if(setUncancellableInternal()){
V result = task.call();
setSuccessInternal(result);
}
}catch(Throwable e){
setFailureInternal(e);
}
IO调用会返回一个ChannelFuture的实例,通过该实例可以查看IO操作的结果和状态,
ChannelFuture有完成和未完成两种状态,当IO操作开始,就会创建一个ChannelFuture的实例,该实例初始是未完成状态,它不是成功,失败,或者取消,因为IO操作还没有完成,如果IO操作完成了那么将会有成功,失败,和取消状态,
* +---------------------------+
* | Completed successfully |
* +---------------------------+
* +----> isDone() = <b>true</b> |
* +--------------------------+ | | isSuccess() = <b>true</b> |
* | Uncompleted | | +===========================+
* +--------------------------+ | | Completed with failure |
* | isDone() = <b>false</b> | | +---------------------------+
* | isSuccess() = false |----+----> isDone() = <b>true</b> |
* | isCancelled() = false | | | cause() = <b>non-null</b> |
* | cause() = null | | +===========================+
* +--------------------------+ | | Completed by cancellation |
* | +---------------------------+
* +----> isDone() = <b>true</b> |
* | isCancelled() = <b>true</b> |
* +---------------------------+
该类提供了很多方法用来检查IO操作是否完成,等待完成,和接受IO操作的结果。还可以添加ChannelFutureListener的监听器,这样IO操作完成时就可以得到提醒
* 强烈建议使用addListener而不是await。
* addListener是非阻塞的,它简单的添加指定的ChannelFutureListener到ChannelFuture中,
* IO线程将在当绑定在这个future的IO操作完成时,触发这个触发器,优点是提高效率和资源的利用率
* await()是一个阻塞方法,一旦调用,调用线程将会阻塞直到IO操作完成。优点是容易实现顺序逻辑
Netty中的Future的更多相关文章
- Netty 中的异步编程 Future 和 Promise
Netty 中大量 I/O 操作都是异步执行,本篇博文来聊聊 Netty 中的异步编程. Java Future 提供的异步模型 JDK 5 引入了 Future 模式.Future 接口是 Java ...
- Netty中的连接管理
连接管理是我们首先需要关注的,检测空闲连接以及超时对于及时释放资源来说是至关重要的.由于这是一项常见的任务,Netty特地为它提供了几个ChannelHandler实现. 用于空闲连接以及超时的Cha ...
- Reactor 模式在Netty中的应用
Reactor 模式在Netty中的应用 典型的Rector模式 mainReactor 服务端创建成功后,会监听Accept操作,其中ServerSocketchannel中的PipeLine中现在 ...
- Netty(六):Netty中的连接管理(心跳机制和定时断线重连)
何为心跳 顾名思义, 所谓心跳, 即在TCP长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, 通知对方自己还在线, 以确保 TCP 连接的有效性. 为什么需要心跳 因为网络的不可靠性, 有可 ...
- Netty中的那些坑
Netty中的那些坑(上篇) 最近开发了一个纯异步的redis客户端,算是比较深入的使用了一把netty.在使用过程中一边优化,一边解决各种坑.儿这些坑大部分基本上是Netty4对Netty3的改进部 ...
- netty中的websocket
使用WebSocket 协议来实现一个基于浏览器的聊天室应用程序,图12-1 说明了该应用程序的逻辑: (1)客户端发送一个消息:(2)该消息将被广播到所有其他连接的客户端. WebSocket 在从 ...
- Netty中NioEventLoopGroup的创建源码分析
NioEventLoopGroup的无参构造: public NioEventLoopGroup() { this(0); } 调用了单参的构造: public NioEventLoopGroup(i ...
- netty中的发动机--EventLoop及其实现类NioEventLoop的源码分析
EventLoop 在之前介绍Bootstrap的初始化以及启动过程时,我们多次接触了NioEventLoopGroup这个类,关于这个类的理解,还需要了解netty的线程模型.NioEventLoo ...
- Netty中的ChannelFuture和ChannelPromise
在Netty使用ChannelFuture和ChannelPromise进行异步操作的处理 这是官方给出的ChannelFutur描述 * | Completed successfully | * + ...
随机推荐
- MyBatis嵌套查询column传多个参数描述
代码如下,红色部分为关键代码. 注意parameterType要为java.util.HashMap <resultMap id="baseResultMap" type=& ...
- BZOJ2716:[Violet 3]天使玩偶
浅谈离线分治算法:https://www.cnblogs.com/AKMer/p/10415556.html 题目传送门:https://lydsy.com/JudgeOnline/problem.p ...
- BZOJ1293:[SCOI2009]生日礼物
浅谈队列:https://www.cnblogs.com/AKMer/p/10314965.html 题目传送门:https://lydsy.com/JudgeOnline/problem.php?i ...
- Python collections系列之双向队列
双向队列(deque) 一个线程安全的双向队列 1.创建一个双向队列 import collections d = collections.deque() d.append(') d.appendle ...
- kindeditro.js乱码问题
kindeditor.js是用于显示新建邮件时的菜单栏的一个插件,比较好用,但是在引入的时候会出现乱码问题,主要有几个方面原因. 1.编码方式不对,要设置成utf8. <script chars ...
- .NET Framework、C#、CLR和Visual Studo之间的版本关系
.NET Framework.C#.CLR和Visual Studo之间的版本关系 参考 .NET Framework.C#.CLR和Visual Studo之间的版本关系
- 框架Mockito
一.什么是mock测试,什么是mock对象? 先来看看下面这个示例: 从上图可以看出如果我们要对A进行测试,那么就要先把整个依赖树构建出来,也就是BCDE的实例. 一种替代方案就是使用mocks 从图 ...
- 2016.8.11 DataTable合并及排除重复方法
合并: DataTable pros=xxx; DataTable pstar=yyy; //将两张DataTable合成一张 foreach (DataRow dr in pstar.Rows) { ...
- springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能
转自:https://blog.csdn.net/thinkingcao/article/details/52472252 C 所用到的jar包 数据库表 数据库表就不用教大家了,一张表,很简 ...
- NSOperation/NSOperationQueue详细使用介绍
一.简介 (1)是使用GCD实现的一套Objective-C的API (2)是面向对象的线程技术 (3)提供了一些在GCD中不容易实现的特性,如:限制最大并发数量.操作之间的依赖关系 NSOp ...