可写的特殊Future接口:Promise
Promise
接口继承了Future
接口,是可写的:
public interface Promise<V> extends Future<V>
ChannelPromise
接口继承了ChannelFuture
和Promise
接口
public interface ChannelPromise extends ChannelFuture, Promise<Void> {
......
@Override
ChannelPromise setSuccess(Void result);
@Override
ChannelPromise setFailure(Throwable cause);
......
}
实现类DefaultChannelPromise
如下:它持有Channel
和EventExecutor
对象,setSuccess
,setFailure
,addListener
,sync
等方法大多使用父类的实现。
// 建议使用Channel.newPromise(),而不是构造函数
public class DefaultChannelPromise extends DefaultPromise<Void> implements ChannelPromise, FlushCheckpoint {
private final Channel channel;
private long checkpoint;
public DefaultChannelPromise(Channel channel, EventExecutor executor) {
super(executor);
this.channel = checkNotNull(channel, "channel");
}
@Override
protected EventExecutor executor() {
EventExecutor e = super.executor();
if (e == null) {
return channel().eventLoop();
} else {
return e;
}
}
@Override
public ChannelPromise setSuccess(Void result) {
super.setSuccess(result);
return this;
}
@Override
public ChannelPromise setFailure(Throwable cause) {
super.setFailure(cause);
return this;
}
@Override
public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
super.addListener(listener);
return this;
}
@Override
public ChannelPromise sync() throws InterruptedException {
super.sync();
return this;
}
......
}
父类DefaultPromise
:
@Override
public Promise<V> setSuccess(V result) {
// 1.任务成功,通知监听器
if (setSuccess0(result)) {
notifyListeners();
return this;
}
throw new IllegalStateException("complete already: " + this);
}
@Override
public Promise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener) {
checkNotNull(listener, "listener");
synchronized (this) {
addListener0(listener);
}
// 2. 如果任务已经完成,立即通知监听器
if (isDone()) {
notifyListeners();
}
return this;
}
- 任务执行成功完成时,调用
setSuccess
,同时通知所有监听器notifyListeners
。 - 添加监听器时,如果此时任务已经完成,则立即通知监听器
notifyListeners
。