美文网首页Netty源码分析系列
Netty源码分析系列--11. Promise接口

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

作者: ted005 | 来源:发表于2018-11-08 00:30 被阅读50次

    可写的特殊Future接口:Promise

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

    public interface Promise<V> extends Future<V>
    

    ChannelPromise接口继承了ChannelFuturePromise接口

    public interface ChannelPromise extends ChannelFuture, Promise<Void> {
    
        ......
        
        @Override
        ChannelPromise setSuccess(Void result);
        
        @Override
        ChannelPromise setFailure(Throwable cause);
        
        ......
        
    }
    

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

    //  建议使用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

    相关文章

      网友评论

        本文标题:Netty源码分析系列--11. Promise接口

        本文链接:https://www.haomeiwen.com/subject/mdcixqtx.html