Netty 之 DefaultPromise 源码解析

概述

promise 是可写的 future, 因为 future 不支持写操作接口,netty 使用 promise 扩展了 future, 可以对异步操作结果进行设置。

DefaultPromise 继承关系

Promise 接口定义


从接口定义可以看出,Promise 在 Future 接口的基础上扩展了,可写的接口。比如 setSuccess()、setFailure() 接口。还支持添加 listener,当执行完成 Promise 后自动回调添加的 listener,这样就不用再通过 get 阻塞的方式进行处理,提高执行效率。

DefaultPromise 成员变量

public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> {
    // 使用 CAS 进行更新执行结果 result 字段。
    private static final AtomicReferenceFieldUpdater<DefaultPromise, Object> RESULT_UPDATER =
            AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class, Object.class, "result");
    // result 的几种 value
    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;
    // 执行的线程池
    private final EventExecutor executor;

DefaultPromise 是通过 CAS 来进行更新执行的结果 result 字段的。
如果执行完成,无返回值则 result = SUCCESS。 有返回值则 result = 执行结果。
如果执行未完成,result = UNCANCELLABLE。
如果执行异常,result = CANCELLATION_CAUSE_HOLDER。

设置执行成功结果

@Override
public Promise<V> setSuccess(V result) {
    if (setSuccess0(result)) {
        notifyListeners();
        return this;
    }
    throw new IllegalStateException("complete already: " + this);
}

1、调用 setSuccess0() 方法设置执行结果
2、如果设置成功则执行 所有通过addListener(GenericFutureListener<? extends Future<? super V>> listener)方法添加的 listener,并返回当前的 Promise。
3、执行失败抛出 IllegalStateException 异常

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

private boolean setValue0(Object 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();
    }
}

1、如果 result == null 则设置为 SUCCESS,然后调用 setValue0() 方法
2、通过 CAS 设置 DefaultPromise.result 值, 判断result 是否为 null 或者 UNCANCELLABLE,如果是则进行修改。如果不是说明已经执行完成(可能成功或失败)。然后调用checkNotifyWaiters() 方法进行唤醒所有 调用 DefaultPromise.get() 获取结果的线程。

3、根据 waiters 进行判断是否有需要唤醒的线程。每一次调用 get() 获取Promise执行结果的时候都会调用 incWaiters() 方法 ++waiters,执行完后调用 decWaiters() 进行 --waiters。

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

获取 EventExecutor ,其实就是 EventLoop,判断执行 EventExecutor 的线程是否和当前线程一致,如果一致则调用 notifyListenersNow() 方法执行 listener。不一致则将任务封装成 Runnable 提交到任务队列中等待执行。

private void notifyListenersNow() {
    Object listeners;
    synchronized (this) {
        // Only proceed if there are listeners to notify and we are not already notifying listeners.
        if (notifyingListeners || this.listeners == null) {
            return;
        }
        notifyingListeners = true;
        listeners = this.listeners;
        this.listeners = null;
    }
    for (;;) {
        if (listeners instanceof DefaultFutureListeners) {
            notifyListeners0((DefaultFutureListeners) listeners);
        } else {
            notifyListener0(this, (GenericFutureListener<?>) listeners);
        }
        synchronized (this) {
            if (this.listeners == null) {
                // Nothing can throw from within this method, so setting notifyingListeners back to false does not
                // need to be in a finally block.
                notifyingListeners = false;
                return;
            }
            listeners = this.listeners;
            this.listeners = null;
        }
    }
}

1、获取 listeners 值 并将 this.listeners 置为 null
listeners = this.listeners;
this.listeners = null;
2、调用 notifyListeners0() 或 notifyListener0() 方法执行 listeners
3、执行完 listeners 后,再次判断 this.listeners 是否为null,如果不为null,说明在执行过程中又有新的 listeners 添加进来,继续 for 循环执行。如果为 null 则return 退出 死循环。

private void notifyListeners0(DefaultFutureListeners listeners) {
    GenericFutureListener<?>[] a = listeners.listeners();
    int size = listeners.size();
    for (int i = 0; i < size; i ++) {
        notifyListener0(this, a[i]);
    }
}

@SuppressWarnings({ "unchecked", "rawtypes" })
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);
        }
    }
}

执行添加的 listeners。

获取执行结果

@Override
public V get() throws InterruptedException, ExecutionException {
    await();

    Throwable cause = cause();
    if (cause == null) {
        return getNow();
    }
    if (cause instanceof CancellationException) {
        throw (CancellationException) cause;
    }
    throw new ExecutionException(cause);
}

1、首先判断该 Promise 是否执行完成,如果执行完成则继续执行,如果没有执行完成则挂起当前线程。
2、判断执行是否有异常,如果没有异常则直接调用 getNow() 方法获取返回值。
3、如果有异常则首先判断异常是否是 CancellationException异常,如果是则直接抛出,不是则使用 ExecutionException 异常包装再抛出。

@Override
public Promise<V> 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;
}

1、通过 isDone() 方法判断是否执行完成,如果执行完成直接返回
2、判断当前线程是否被中断,如果中断则直接抛出 InterruptedException 异常
3、检查执行 Promise 任务的线程是否是当前线程,如果是当前线程再调用 await() 就会发生死锁的情况,抛出 BlockingOperationException 异常。就相当于获取结果和执行都是当前线程,自己调用 await() 方法把自己阻塞掉了。

@SuppressWarnings("unchecked")
@Override
public V getNow() {
    Object result = this.result;
    if (result instanceof CauseHolder || result == SUCCESS || result == UNCANCELLABLE) {
        return null;
    }
    return (V) result;
}

如果 Promise 执行无返回结果,当执行完成时会把 result 设置为 SUCCESS,这里判断如果有异常、SUCCESS 和 UNCANCELLABLE 则返回 null,否则返回执行结果 result。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章