io.netty:netty-all:4.1.33.Final
Promise
,Future
和 Callback
。其中的Future
表示一个可能还没有实际完成的异步任务的结果,针对这个结果可以添加Callback
以便在任务执行成功或失败后做出对应的操作,而Promise
交由任务执行者,任务执行者通过Promise
可以标记任务完成或者失败。 可以说这一套模型是很多异步非阻塞架构的基础。Netty 4中正提供了这种Future/Promise
异步模型。Future/Promise
模型,在Netty里面也是这样定义的:
Future
接口定义了isSuccess()
,isCancellable()
,cause()
,这些判断异步执行状态的方法。(只读)Promise
接口在extends Future
的基础上增加了setSuccess()
, setFailure()
这些方法(可写)。即Promise
是可写的Future
。Future
接口就是用来封装异步操作的执行状态的,在执行异步操作时,可以立马返回一个Future
,Future
可以sync
来等待执行结果,如果有些操作要等到Future
代表的异步操作完了才能执行,可以通过future.addListener()
的方式来在之前的异步操作完成的时候执行新的操作。Future
,内部其实是Promise
,异步的时候一般是初始线程代码里封装一个Runnable,创建一个Promise
, 把Runnable放到其他线程池去执行,执行的时候把Promise
对象传进去(通过final关键字),在run()方法里结束时去改变Promise
的状态或设置结果的值。初始线程在设置异步操作时可以立马返回Future
(其实是Promise
),可以根据情况选择future.sync()
来同步等待结果或者future.addListener()
来设置异步操作。java.util.concurrent.Future
是Java提供的接口,表示异步执行的状态。
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
Netty中所有的I/O操作都是异步执行的,例如你连接一个主机默认是异步完成的;写入/发送消息同样也是异步。也就是说操作不会直接执行,而是会等一会执行,因为你不知道返回的操作结果是成功还是失败,但是需要有检查是否成功的方法或者是注册监听来通知;Netty使用io.netty.util.concurrent.Future
(继承JDK的Future
)和 ChannelFuture
来达到这种目的。Future
注册一个监听,当操作成功或失败时会通知。ChannelFuture
封装的是一个操作的相关信息,操作被执行时会立刻返回ChannelFuture
。
ChannelFuture
接口扩展了Netty的o.netty.util.concurrent.Future
接口,表示一种没有返回值的异步调用,同时关联了Channel
,跟一个Channel
绑定(因此命名为ChannelFuture
)。ChannelFuture
接口其addListener()
方法注册一个ChannelFutureListener
,以便在某个操作完成时(无论是否成功)得到通知
public interface ChannelFuture extends Future<Void> {
Channel channel();
@Override
ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
@Override
ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners);
@Override
ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener);
@Override
ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners);
@Override
ChannelFuture sync() throws InterruptedException;
@Override
ChannelFuture syncUninterruptibly();
@Override
ChannelFuture await() throws InterruptedException;
@Override
ChannelFuture awaitUninterruptibly();
boolean isVoid();
}
ChannelFuture
有两种状态,Uncompleted
和Completed
,当开始一个I/O操作时,一个新的ChannelFuture
被创建,此时它处于Uncompleted
状态(非成功、非失败、非取消),因为I/O操作此时还没有完成。一旦I/O操作完成,ChannelFuture
将会被设置为Completed
(操作成功、操作失败或者操作被取消)
+---------------------------+
| Uncompleted 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 |
+---------------------------+
不要混淆I/O超时和等待超时。使用await(long)
, await(long, TimeUnit)
, awaitUninterruptibly(long)
,或者awaitUninterruptibly(long, TimeUnit)
指定的超时值与I/O超时完全无关,即如果ChannelFuture
超时后,如果没有关闭连接资源,随后连接依旧可能会成功,这会导致严重的问题。如果I/O操作超时,则将来标记为"已完成但失败",比如连接超时,应该通过特定的选项来配置,而不是通过等待超时来达到目的。
//永远不要这样写(等待超时)
Bootstrap b = ...;
ChannelFuture f = b.connect(...);
f.awaitUninterruptibly(10, TimeUnit.SECONDS);
if (f.isCancelled()) {
//被取消
} else if (!f.isSuccess()) {
f.cause().printStackTrace();
} else {
//连接建立成功
}
// 好的方式(通过连接超时选项来配置)
Bootstrap b = ...;
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
ChannelFuture f = b.connect(...);
f.awaitUninterruptibly();
//连接必然完成
assert f.isDone();
if (f.isCancelled()) {
// 被取消
} else if (!f.isSuccess()) {
f.cause().printStackTrace();
} else {
// 连接建立成功
}
ChannelHandler
中的事件处理程序方法通常由I/O线程调用。如果事件处理程序方法(由I/O线程调用)调用await()
,则它正在等待的I/O操作可能永远不会完成,因为await()
可以阻止它正在等待的I/O
操作,会造成死锁(这不是两个线程互相等待的死锁,而是一个线程的死锁,自己把自己挂死)。
//永远不要这样写
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ChannelFuture future = ctx.channel().close();
future.awaitUninterruptibly();
// 执行关闭后的操作...
}
//推荐的写法
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ChannelFuture future = ctx.channel().close();
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
// 执行关闭后的操作...
}
});
}
Netty扩展了Java的Future
,最主要的改进就是增加了监听器Listener
接口,通过监听器可以让异步执行更加有效率,不需要通过get来等待异步执行结束,而是通过监听器回调来精确地控制异步执行结束的时间点。Netty推荐使用future.addListener
的方式来回调异步执行的结果,这种方式优于future.get()
,能够更精确地把握异步执行结束的时间。
public interface Future<V> extends java.util.concurrent.Future<V> {
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);
Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
...省略...
}
io.netty.util.concurrent.Promise
接口扩展了Netty的io.netty.util.concurrent.Future
接口,它表示一种可写的Future
,就是可以设置异步执行的结果
public interface Promise<V> extends Future<V> {
Promise<V> setSuccess(V result);
boolean trySuccess(V result);
Promise<V> setFailure(Throwable cause);
boolean tryFailure(Throwable cause);
}
ChannelPromise
接口扩展了Promise
和ChannelFuture
,绑定了Channel
,既可写异步执行结果,又具备了监听者的功能,是Netty实际编程使用的表示异步执行的接口
public interface ChannelPromise extends ChannelFuture, Promise<Void> {
@Override
Channel channel();
@Override
ChannelPromise setSuccess(Void result);
ChannelPromise setSuccess();
boolean trySuccess();
...省略...
}
DefaultChannelPromise
是ChannelPromise
的实现类,它是实际运行时的Promoise
实例。Channel
接口提供了newPromise
方法,表示Channel
要创建一个异步执行的动作
public interface Channel extends AttributeMap, Comparable<Channel> {
ChannelPromise newPromise();
}
public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
public ChannelPromise newPromise() {
return new DefaultChannelPromise(this);
}
}