Netty源码分析系列--11. Promise接口

可写的特殊Future接口:Promise

Promise接口继承了Future接口,是可写的

public interface Promise extends Future

ChannelPromise接口继承了ChannelFuturePromise接口

public interface ChannelPromise extends ChannelFuture, Promise {

    ......
    
    @Override
    ChannelPromise setSuccess(Void result);
    
    @Override
    ChannelPromise setFailure(Throwable cause);
    
    ......
    
}

实现类DefaultChannelPromise如下:它持有ChannelEventExecutor对象setSuccesssetFailureaddListenersync等方法大多使用父类的实现。

//  建议使用Channel.newPromise(),而不是构造函数
public class DefaultChannelPromise extends DefaultPromise 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> listener) {
        super.addListener(listener);
        return this;
    }

    @Override
    public ChannelPromise sync() throws InterruptedException {
        super.sync();
        return this;
    }
    
    ......
}

父类DefaultPromise:

@Override
public Promise setSuccess(V result) {
    // 1.任务成功,通知监听器
    if (setSuccess0(result)) {
        notifyListeners();
        return this;
    }
    throw new IllegalStateException("complete already: " + this);
}

@Override
public Promise addListener(GenericFutureListener> listener) {
    checkNotNull(listener, "listener");

    synchronized (this) {
        addListener0(listener);
    }

    // 2. 如果任务已经完成,立即通知监听器
    if (isDone()) {
        notifyListeners();
    }

    return this;
}
  • 任务执行成功完成时,调用setSuccess,同时通知所有监听器notifyListeners
  • 添加监听器时,如果此时任务已经完成,则立即通知监听器notifyListeners

你可能感兴趣的:(Netty源码分析系列--11. Promise接口)