Netty源码分析-DefaultPromise

Netty-Future基类,所有IO操作都返回该实现或其子类

DefaultPromise源码分析:


//Netty-Future基类,所有IO操作都返回该实现或其子类
public class DefaultPromise extends AbstractFuture implements Promise {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultPromise.class);
    private static final InternalLogger rejectedExecutionLogger =
            InternalLoggerFactory.getInstance(DefaultPromise.class.getName() + ".rejectedExecution");
    private static final int MAX_LISTENER_STACK_DEPTH = Math.min(8,
            SystemPropertyUtil.getInt("io.netty.defaultPromise.maxListenerStackDepth", 8));
    @SuppressWarnings("rawtypes")

    //原子引用更新工具,负责以原子方式更新result变量的值
    private static final AtomicReferenceFieldUpdater RESULT_UPDATER =
            AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class, Object.class, "result");
    //成功常量对象
    private static final Object SUCCESS = new Object();
    //取消常量对象
    private static final Object UNCANCELLABLE = new Object();
    //封装异常对象
    private static final CauseHolder CANCELLATION_CAUSE_HOLDER = new CauseHolder(ThrowableUtil.unknownStackTrace(
            new CancellationException(), DefaultPromise.class, "cancel(...)"));

    //执行结果
    private volatile Object result;
    //执行IO的线程
    private final EventExecutor executor;
    
    //回调监听器
    //{@link GenericFutureListener} or a {@link DefaultFutureListeners}.
    private Object listeners;
   
    //阻塞在此监听器上的线程数量
    private short waiters;

    //是否调用过监听器
    private boolean notifyingListeners;

    //构造参数
    public DefaultPromise(EventExecutor executor) {
        this.executor = checkNotNull(executor, "executor");
    }

    //设置result
    @Override
    public Promise setSuccess(V result) {
        //设置成功调用listeners
        if (setSuccess0(result)) {
            notifyListeners();
            return this;
        }
        throw new IllegalStateException("complete already: " + this);
    }

    //尝试设置result
    @Override
    public boolean trySuccess(V result) {
        if (setSuccess0(result)) {
            notifyListeners();
            return true;
        }
        return false;
    }

    //设置异常
    @Override
    public Promise setFailure(Throwable cause) {
        if (setFailure0(cause)) {
            notifyListeners();
            return this;
        }
        throw new IllegalStateException("complete already: " + this, cause);
    }

    //尝试设置异常
    @Override
    public boolean tryFailure(Throwable cause) {
        if (setFailure0(cause)) {
            notifyListeners();
            return true;
        }
        return false;
    }

    //设置取消
    @Override
    public boolean setUncancellable() {
        //当result为null时设置变量为UNCANCELLABLE
        if (RESULT_UPDATER.compareAndSet(this, null, UNCANCELLABLE)) {
            return true;
        }
        Object result = this.result;
        return !isDone0(result) || !isCancelled0(result);
    }

    //判断是否成功
    @Override
    public boolean isSuccess() {
        //result不是其它状态表示成功
        Object result = this.result;
        return result != null && result != UNCANCELLABLE && !(result instanceof CauseHolder);
    }

    //是否可以取消,result==null则可以
    @Override
    public boolean isCancellable() {
        return result == null;
    }

    //获取异常对象
    @Override
    public Throwable cause() {
        Object result = this.result;
        return (result instanceof CauseHolder) ? ((CauseHolder) result).cause : null;
    }

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

        //锁定添加
        synchronized (this) {
            addListener0(listener);
        }

        //完成则通知
        if (isDone()) {
            notifyListeners();
        }

        return this;
    }

    //移除监听器
    @Override
    public Promise removeListener(final GenericFutureListener> listener) {
        checkNotNull(listener, "listener");

        synchronized (this) {
            removeListener0(listener);
        }

        return this;
    }

    //线程阻塞
    @Override
    public Promise await() throws InterruptedException {
        //如果已完成返回自己不阻塞
        if (isDone()) {
            return this;
        }

        //当前线程终端抛出异常
        if (Thread.interrupted()) {
            throw new InterruptedException(toString());
        }

        //检测死锁
        checkDeadLock();

        //同步锁
        synchronized (this) {
            //未完成
            while (!isDone()) {
                //增加锁定计数
                incWaiters();
                try {
                    //锁定线程
                    wait();
                } finally {
                    //减少计数器
                    decWaiters();
                }
            }
        }
        //返回自己
        return this;
    }

    //跟上面方法一样,忽略线程的中断状态
    @Override
    public Promise 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;
    }

    //阻塞一段时间
    @Override
    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        return await0(unit.toNanos(timeout), true);
    }

    //阻塞一段时间-忽略异常
    @Override
    public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
        try {
            return await0(unit.toNanos(timeout), false);
        } catch (InterruptedException e) {
            // Should not be raised at all.
            throw new InternalError();
        }
    }

    //除了3种状态以外直接返回result
    @SuppressWarnings("unchecked")
    @Override
    public V getNow() {
        Object result = this.result;
        if (result instanceof CauseHolder || result == SUCCESS || result == UNCANCELLABLE) {
            return null;
        }
        return (V) result;
    }

    //取消
    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        //设置取消状态
        if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) {
            //唤醒线程
            checkNotifyWaiters();
            //通知
            notifyListeners();
            return true;
        }
        return false;
    }

    //是否取消
    @Override
    public boolean isCancelled() {
        return isCancelled0(result);
    }

    //是否完成
    @Override
    public boolean isDone() {
        return isDone0(result);
    }

    //sync-等待isdone返回true
    @Override
    public Promise sync() throws InterruptedException {
        await();
        rethrowIfFailed();
        return this;
    }

    //sync-忽略线程中断异常
    @Override
    public Promise syncUninterruptibly() {
        awaitUninterruptibly();
        rethrowIfFailed();
        return this;
    }

    //通知监听器
    private void notifyListeners() {
        EventExecutor executor = executor();
        //如果在eventLoop当中直接调用
        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;
            }
        }

        //放入eventLoop当中直接调用
        safeExecute(executor, new Runnable() {
            @Override
            public void run() {
                notifyListenersNow();
            }
        });
    }

    //调用监听器
    private static void notifyListener0(Future future, GenericFutureListener l) {
        try {
            l.operationComplete(future);
        } catch (Throwable t) {
            if (logger.isWarnEnabled()) {
                logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationComplete()", t);
            }
        }
    }

    //添加监听器
    private void addListener0(GenericFutureListener> listener) {
        //为空直接赋值
        if (listeners == null) {
            listeners = listener;
            //数组直接添加
        } else if (listeners instanceof DefaultFutureListeners) {
            ((DefaultFutureListeners) listeners).add(listener);
        } else {
            //第二次添加创建数组
            listeners = new DefaultFutureListeners((GenericFutureListener) listeners, listener);
        }
    }

    //移除监听器
    private void removeListener0(GenericFutureListener> listener) {
        if (listeners instanceof DefaultFutureListeners) {
            ((DefaultFutureListeners) listeners).remove(listener);
        } else if (listeners == listener) {
            listeners = null;
        }
    }


    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) {
        //如果为空或者可以取消,设置objResult
        if (RESULT_UPDATER.compareAndSet(this, null, objResult) ||
            RESULT_UPDATER.compareAndSet(this, UNCANCELLABLE, objResult)) {
            //设置完成后唤醒阻塞线程
            checkNotifyWaiters();
            return true;
        }
        return false;
    }

    //唤醒阻塞在此的线程
    private synchronized void checkNotifyWaiters() {
        if (waiters > 0) {
            notifyAll();
        }
    }

    //阻塞计数器++
    private void incWaiters() {
        if (waiters == Short.MAX_VALUE) {
            throw new IllegalStateException("too many waiters: " + this);
        }
        ++waiters;
    }

    //阻塞计数器--
    private void decWaiters() {
        --waiters;
    }

    //如果存在移除抛出
    private void rethrowIfFailed() {
        Throwable cause = cause();
        if (cause == null) {
            return;
        }

        PlatformDependent.throwException(cause);
    }

    //
    private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException {
        //如果已经完成则返回自己不阻塞
        if (isDone()) {
            return true;
        }

        //
        if (timeoutNanos <= 0) {
            return isDone();
        }

        if (interruptable && Thread.interrupted()) {
            throw new InterruptedException(toString());
        }

        checkDeadLock();

        //等待固定时间
        long startTime = System.nanoTime();
        long waitTime = timeoutNanos;
        boolean interrupted = false;
        try {
            for (;;) {
                synchronized (this) {
                    if (isDone()) {
                        return true;
                    }
                    incWaiters();
                    try {
                        wait(waitTime / 1000000, (int) (waitTime % 1000000));
                    } catch (InterruptedException e) {
                        if (interruptable) {
                            throw e;
                        } else {
                            interrupted = true;
                        }
                    } finally {
                        decWaiters();
                    }
                }
                if (isDone()) {
                    return true;
                } else {
                    waitTime = timeoutNanos - (System.nanoTime() - startTime);
                    if (waitTime <= 0) {
                        return isDone();
                    }
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }

    //是否已经取消
    private static boolean isCancelled0(Object result) {
        return result instanceof CauseHolder && ((CauseHolder) result).cause instanceof CancellationException;
    }

    //是否已经完成
    private static boolean isDone0(Object result) {
        return result != null && result != UNCANCELLABLE;
    }

    private static final class CauseHolder {
        final Throwable cause;
        CauseHolder(Throwable cause) {
            this.cause = cause;
        }
    }

    private static void safeExecute(EventExecutor executor, Runnable task) {
        try {
            executor.execute(task);
        } catch (Throwable t) {
            rejectedExecutionLogger.error("Failed to submit a listener notification task. Event loop shut down?", t);
        }
    }
}

 

你可能感兴趣的:(Netty)