Netty 4.1.X源代码 再读1 Future剖析


在Apache  Mina 中定义了Future操作。 Netty4.1.x 对Future操作进行的重新设计。


io.netty.util.concurrent 包中定义了public interface Future<V> extends java.util.concurrent.Future<V>  接口,该接口实现JDK  Future 接口。


io.netty.util.concurrent.Future 接口表示异步操作结果的接口。The result of an asynchronous operation.


public interface Future<V> extends java.util.concurrent.Future<V> {


    boolean isSuccess();

    boolean isCancellable();


    Throwable cause();

    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);


  
    Future<V> sync() throws InterruptedException;


    Future<V> syncUninterruptibly();


    Future<V> await() throws InterruptedException;


    Future<V> awaitUninterruptibly();


  
    boolean await(long timeout, TimeUnit unit) throws InterruptedException;


   
    boolean await(long timeoutMillis) throws InterruptedException;


 
    boolean awaitUninterruptibly(long timeout, TimeUnit unit);


   
    boolean awaitUninterruptibly(long timeoutMillis);


 
    V getNow();

    boolean cancel(boolean mayInterruptIfRunning);
}

Future 接口定义了异步操作结果获取,监听器以及异步操作转换成同步等接口。


同时,定义了一个public interface Promise<V> extends Future<V> {}     Special  Future  which is writable.  Promise 表示可以写入结果的Future.


public interface Promise<V> extends Future<V> {


    /**
     * Marks this future as a success and notifies all
     * listeners.
     *
     * If it is success or failed already it will throw an {@link IllegalStateException}.
     */
    Promise<V> setSuccess(V result);


    /**
     * Marks this future as a success and notifies all
     * listeners.
     *
     * @return {@code true} if and only if successfully marked this future as
     *         a success. Otherwise {@code false} because this future is
     *         already marked as either a success or a failure.
     */
    boolean trySuccess(V result);


    /**
     * Marks this future as a failure and notifies all
     * listeners.
     *
     * If it is success or failed already it will throw an {@link IllegalStateException}.
     */
    Promise<V> setFailure(Throwable cause);


    /**
     * Marks this future as a failure and notifies all
     * listeners.
     *
     * @return {@code true} if and only if successfully marked this future as
     *         a failure. Otherwise {@code false} because this future is
     *         already marked as either a success or a failure.
     */
    boolean tryFailure(Throwable cause);


    /**
     * Make this future impossible to cancel.
     *
     * @return {@code true} if and only if successfully marked this future as uncancellable or it is already done
     *         without being cancelled.  {@code false} if this future has been cancelled already.
     */
    boolean setUncancellable();


    @Override
    Promise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);


    @Override
    Promise<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);


    @Override
    Promise<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);


    @Override
    Promise<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);


    @Override
    Promise<V> await() throws InterruptedException;


    @Override
    Promise<V> awaitUninterruptibly();


    @Override
    Promise<V> sync() throws InterruptedException;


    @Override
    Promise<V> syncUninterruptibly();
}


在Promise接口中主要有 Promise<V> setSuccess(V result);  、  Promise<V> setFailure(Throwable cause); 来设置Future异步的结果。




在Future定义了GenericFutureListener 监听器。当Future操作完成时,void operationComplete(F future) throws Exception; 接口方法将会调用。

/**
 * Listens to the result of a {@link Future}.  The result of the asynchronous operation is notified once this listener
 * is added by calling {@link Future#addListener(GenericFutureListener)}.
 */
public interface GenericFutureListener<F extends Future<?>> extends EventListener {

    /**
     * Invoked when the operation associated with the {@link Future} has been completed.
     *
     * @param future  the source {@link Future} which called this callback
     */
    void operationComplete(F future) throws Exception;
}


DefaultPromise 为Future、Promise接口的默认实现。  实现方式与Apache  Mina  中DefaultIoFuture 实现原理一样。


public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {


   private static final AtomicReferenceFieldUpdater<DefaultPromise, Object> RESULT_UPDATER;
    private static final Signal SUCCESS = Signal.valueOf(DefaultPromise.class, "SUCCESS");
    private static final Signal UNCANCELLABLE = Signal.valueOf(DefaultPromise.class, "UNCANCELLABLE");


static {
        @SuppressWarnings("rawtypes")
        AtomicReferenceFieldUpdater<DefaultPromise, Object> updater =
                PlatformDependent.newAtomicReferenceFieldUpdater(DefaultPromise.class, "result");
        RESULT_UPDATER = updater == null ? AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class,
                                                                                  Object.class, "result") : updater;
    }


 private volatile Object result;
    private final EventExecutor executor;
    /**
     * One or more listeners. Can be a {@link GenericFutureListener} or a {@link DefaultFutureListeners}.
     * If {@code null}, it means either 1) no listeners were added yet or 2) all listeners were notified.
     *
     * Threading - synchronized(this). We must support adding listeners when there is no EventExecutor.
     */
    private Object listeners;
    /**
     * Threading - synchronized(this). We are required to hold the monitor to use Java's underlying wait()/notifyAll().
     */
    private short waiters;


    /**
     * Threading - synchronized(this). We must prevent concurrent notification and FIFO listener notification if the
     * executor changes.
     */
    private boolean notifyingListeners;



   @Override
    public Promise<V> awaitUninterruptibly() {
        if (isDone()) {
            return this;
        }


        checkDeadLock();


        boolean interrupted = false;
        synchronized (this) {
            while (!isDone()) {
                incWaiters();
                try {
                    wait();
                } catch (InterruptedException e) {
                    // Interrupted while waiting.
                    interrupted = true;
                } finally {
                    decWaiters();
                }
            }
        }


        if (interrupted) {
            Thread.currentThread().interrupt();
        }


        return this;
    }


  private boolean setSuccess0(V result) {
        return setValue0(result == null ? SUCCESS : result);
    }


    private boolean setFailure0(Throwable cause) {
        return setValue0(new CauseHolder(checkNotNull(cause, "cause")));
    }


    private boolean setValue0(Object objResult) {
        if (RESULT_UPDATER.compareAndSet(this, null, objResult) ||
            RESULT_UPDATER.compareAndSet(this, UNCANCELLABLE, objResult)) {
            checkNotifyWaiters();
            return true;
        }
        return false;
    }




    private void notifyListeners() {
        EventExecutor executor = executor();
        if (executor.inEventLoop()) {
            final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get();
            final int stackDepth = threadLocals.futureListenerStackDepth();
            if (stackDepth < MAX_LISTENER_STACK_DEPTH) {
                threadLocals.setFutureListenerStackDepth(stackDepth + 1);
                try {
                    notifyListenersNow();
                } finally {
                    threadLocals.setFutureListenerStackDepth(stackDepth);
                }
                return;
            }
        }


        safeExecute(executor, new Runnable() {
            @Override
            public void run() {
                notifyListenersNow();
            }
        });
    }



    private void addListener0(GenericFutureListener<? extends Future<? super V>> listener) {
        if (listeners == null) {
            listeners = listener;
        } else if (listeners instanceof DefaultFutureListeners) {
            ((DefaultFutureListeners) listeners).add(listener);
        } else {
            listeners = new DefaultFutureListeners((GenericFutureListener<? extends Future<V>>) listeners, listener);
        }
    }



}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值