DefaultPromise

341 阅读9分钟

image.png

DefaultPromise.svg

DefaultPromise

类签名

继承AbstractFuture实现Promise

public class DefaultPromise extends AbstractFuture implements Promise

static的内部类

CauseHolder

  • private static final class CauseHolder { final Throwable cause; CauseHolder(Throwable cause) { this.cause = cause; } }
  • 这个内部类是static,并且是private说明说这个类只有DefaultPromise会使用到

StacklessCancellationException

  • 类签名:private static final class StacklessCancellationException extends CancellationException

  • 以为是private 所以这个static的内部类,也只能在DefaultPromise中使用

  • 顾名思义这个类是没有栈信息的异常类

  • 他通过覆写fillInStackTrace,实现没有堆栈信息

    • @Override public Throwable fillInStackTrace() { return this; }
  • 有一个static的方法,可以new一个StacklessCancellationException出来,并且可以为它设置一个栈信息,通过调用Throwable的setStackTrace就可以

LeanCancellationException

  • 顾名思义:高效的CancellationException,只有一行栈信息CANCELLATION_STACK

字段

static 字段

  • MAX_LISTENER_STACK_DEPTH

    • 类型:private static final int
    • 值:Math.min(8, SystemPropertyUtil.getInt("io.netty.defaultPromise.maxListenerStackDepth", 8));
  • RESULT_UPDATER

    • 类型:private static final AtomicReferenceFieldUpdater<DefaultPromise, Object>
    • 值:AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class, Object.class, "result");
  • SUCCESS

    • 类型:private static final Object
    • 值:new Object()
  • UNCANCELLABLE

    • 类型:private static final Object
    • 值:new Object()
  • CANCELLATION_CAUSE_HOLDER

    • 类型:private static final CauseHolder
    • 值:new CauseHolder( StacklessCancellationException.newInstance(DefaultPromise.class, "cancel(...)"));
  • CANCELLATION_STACK

    • 类型: private static final StackTraceElement[]
    • 值:CANCELLATION_CAUSE_HOLDER.cause.getStackTrace();

非static字段

  • result

    • 类型:private volatile Object
      
    • 有用 volatile修饰说明这个变量会在多线程的场景中使用
  • listeners

    • 类型: private Object
    • 含义:一个或多个listener,类型可能是GenericFutureListener或者DefaultFutureListeners
    • 如果为null,表示没有任何的listener,或者所有的listener都被通知过了
  • executor

    • 类型: private final EventExecutor
  • waiters

    • 类型: private short
    • 含义:表示有多少线程在等待
  • notifyingListeners

    • 类型: private boolean
    • 含义:表示当前现在通知listener

公有方法

public Promise setSuccess(V result)

  • 语义是:把这个Future设置为成功,并通知所有的监听者,如果这个Future已经是成功或者失败的,则会抛出IllegalStateException异常
  • 最终会调用 private boolean setValue0(Object objResult)这个方法,去设置result字段和通知监听者

public Promise trySuccess(V result)

  • 语义是:把这个Future设置为成功,并通知所有的监听者,如果这个Future已经是成功或者失败的,则不会抛出IllegalStateException异常,只是返回false

public Promise setFailure(Throwable cause)

  • 语义:语义是:把这个Future设置为失败,并通知所有的监听者,如果这个Future已经是成功或者失败的,则会抛出IllegalStateException异常
  • 最终会调用 private boolean setValue0(Object objResult)这个方法,去设置result字段和通知监听者,其中用new CauseHolder(cause)给result字段设置

public boolean tryFailure(Throwable cause)

  • 语义是:把这个Future设置为失败,并通知所有的监听者,如果这个Future已经是成功或者失败的,则不会抛出IllegalStateException异常,只是返回false

public boolean cancel(boolean mayInterruptIfRunning)

  • 语义:取消Future,如果取消成功,那么result会等于CancellationException

    1. 利用cas的方式去更新result,原值是null,目标值是CANCELLATION_CAUSE_HOLDER
  • 2.如果失败返回false,成功则

    • 检查等待者数量并通知等待者checkNotifyWaiters

      • 如果this.waiters > 0则调用notifyAll()
      • 返回this.listeners是否为null
    • 如果监听者不为null,则通知监听者notifyListeners

核心私有方法

private boolean setValue0(Object objResult)

    1. 利用cas的方式去更新result字段

    • 利用AtomicReferenceFieldUpdater去对result做cas
    • 先用原值是null,做cas,如果不成功在用UNCANCELLABLE做cas
  • 2.如果cas成功则通知监听者

    • 检查等待者数量并通知等待者checkNotifyWaiters

      • 如果this.waiters > 0则调用notifyAll()
      • 返回this.listeners是否为null
    • 如果监听者不为null,则通知监听者notifyListeners

  • 3.如果cas失败,则return false,表示setValue0失败了

private void notifyListeners()

  • EventExecutor executor如果在EventLoop中,executor.inEventLoop()

    • 获取当前线程的InternalThreadLocalMap threadLocals

    • 获取InternalThreadLocalMap中的监听器栈深度字段stackDepth:threadLocals.futureListenerStackDepth();

    • 如果栈的深度小于最大监听器栈深度MAX_LISTENER_STACK_DEPTHstackDepth < MAX_LISTENER_STACK_DEPTH则,

      • 将栈深度+1并set到InternalThreadLocalMap中,threadLocals.setFutureListenerStackDepth(stackDepth + 1);
      • 立刻通知监听者notifyListenersNow();
      • 将栈的深度在InternalThreadLocalMap中在恢复原来的值 threadLocals.setFutureListenerStackDepth(stackDepth);
      • return
  • 剩余的情况则调用safeExecute:将notifyListenersNow();的Runnabl提交给EventExecutor executor执行

private void notifyListenersNow()

  • 做 synchronized (this)

    • 如果正在通知监听者或者监听者为null则return:notifyingListeners || this.listeners == null
    • 将正在通知监听者标志notifyingListeners设置为true:notifyingListeners = true;
    • 将this.listeners先赋值给方法局部变量,在将其置为null: listeners = this.listeners; this.listeners = null;
  • 做一个for (;;)

    • 如果listeners的类型是DefaultFutureListeners,则调用 notifyListeners0((DefaultFutureListeners) listeners);否则调用:notifyListener0(this, (GenericFutureListener<?>) listeners);

    • 做一个 synchronized (this)

      • 如果this.listeners == null,则notifyingListeners设置我false,然后return
      • 否则说明这个时候有新的listeners了,那么再次将this.listeners赋值给方法局部变量listeners,同时将this.listeners设置为null,然后接着循环

private void notifyListeners0(DefaultFutureListeners listeners)

  • 拿出DefaultFutureListeners中所有的GenericFutureListener
  • 遍历所有的GenericFutureListener,对之调用notifyListener0(Future future, GenericFutureListener l)

private static void notifyListener0(Future future, GenericFutureListener l)

  • 调用监听器的operationComplete方法进行通知: l.operationComplete(future);并且会catch住异常,只是打日志

共有方法

public boolean setUncancellable()

  • 语义:将这个Future设置为不可取消的,当这个Future被设置为不可取消的或者在调用这个方法前它已经是失败或者成功状态,那么则return true,当这个已经被取消,则return false

    1. 利用RESULT_UPDATER对this.result字段做cas,原值为null,目标值为UNCANCELLABLE如果成功则return true。
    1. 否则,查看当前的这个result的值,判断它是否已经是是终态isDone0(result),如果它不是终态,那么则表明它目前的状态是UNCANCELLABLE,那么返回true,否则进一步判断它是不是已经被取消,如果它不是已取消isCancelled0(result),则return true,其他情况返回false
  • 总结下:

    • 如果this.result == null ,则通过cas把result设置为UNCANCELLABLE,return cas的结果
    • 如果this.result = 成功或者失败,则return true
    • 如果this.result=UNCANCELLABLE, return true
    • 如果this.result=已取消,则return false

核心私有方法

private static boolean isDone0(Object result)

  • this.result != null && result != UNCANCELLABLE;
  • 有终态,<<>>于此时的result 是成功、失败、已取消的其中一种

private static boolean isCancelled0(Object result)

  • result instanceof CauseHolder && ((CauseHolder) result).cause instanceof CancellationException;
  • 已经被取消<<>>于result是CauseHolder的实例,且其中的cause是CancellationException的实例

共有方法

public boolean isSuccess()

  • result != null && result != UNCANCELLABLE && !(result instanceof CauseHolder);
  • 成功等价于result不是null,也不是UNCANCELLABLE,同时不是CauseHolder的实例
  • 总结:成功表示,this.result != null且也不能是失败、已取消、可取消、

public boolean isCancellable()

  • return result == null;
  • 如果result=null,就表明当前的是可以取消,而至于调用了setUncancellable去设置为不可取消,则当cas失败,或者当前Future已经是被取消的,则return false,其他的情况return true

public Throwable cause()

  • 语义:返回Future失败的原因,返回null,如果这个Future是成功的,或者这个Future还没有被完成
    1. 如果this.result 不是CauseHolder的实例,则return null,表明此时result的值是null,成功或者可取消的
  • 2.那么这个时候剩下的状态就剩下两种状态一种是失败一种是已取消;如果此时result=CANCELLATION_CAUSE_HOLDER,那么表示此时的状态是已取消,那么这个时候则new一个LeanCancellationException出来CancellationException ce = new LeanCancellationException(),并且通过cas把result设置为new CauseHolder(ce),然后返回ce,如果cas失败表示此时result的值已经发生改变,则将此时的result.cause返回
  • 3.如果此时的状态是失败,则直接返回result.cause
  • 总结:此处代码的这种写法,一个动机是要减少对于volatile变量的读取,另一个动机是要减少对于异常的创建,同时又不能把static的异常给暴露出去,因为如果static的异常暴露出去了,如果netty的使用方,调用了addSuppressed,则会引起oom,因此次数的处理是,当如果是取消状态的则会用CANCELLATION_CAUSE_HOLDER去表示,但是当使用方要来获取异常的时候则会重新一个LeanCancellationException出来

public boolean isCancelled()

  • return isCancelled0(result);

public boolean isDone()

  • return isDone0(result);

总结一下DefaultPromise的状态

初始化

  • result = null

成功

失败

  • result是CauseHolder的实例,且其中的cause不是CancellationException的实例

不可取消

  • result = UNCANCELLABLE

已取消

  • result是CauseHolder的实例,且其中的cause是CancellationException的实例

其中成功、失败、已取消表示有终态,即isDone会返回true

公有方法

public Promise addListener(GenericFutureListener<? extends Future<? super V>> listener)

    1. 对入参listener判空
    1. 做synchronized (this)然后在其中调用addListener0(listener);
    1. 查询是否已经有终态isDone(),有终态则通知监听者 notifyListeners();
    1. return this

public Promise removeListener(final GenericFutureListener<? extends Future<? super V>> listener)

    1. 对入参listener判空
    1. 做synchronized (this)然后在其中调用removeListener0(listener);

核心私有方法

private void addListener0(GenericFutureListener<? extends Future<? super V>> listener)

  • 如果this.listeners = null,则this.listeners = listener;返回
  • 如果this.listeners是DefaultFutureListeners的实例则((DefaultFutureListeners) listeners).add(listener);
  • 否则则用当前的this.listeners和当前的入参listener为入参new一个DefaultFutureListeners出来:this.listeners = new DefaultFutureListeners((GenericFutureListener<?>) this.listeners, listener);

public Promise removeListener(final GenericFutureListener<? extends Future<? super V>> listener)

  • 如果listeners instanceof DefaultFutureListeners则((DefaultFutureListeners) listeners).remove(listener);
  • 如果listeners == listener则 listeners = null;

公有方法

public Promise await() throws InterruptedException

  • 语义:等待直到这个Future有终态,如果调用线程被打断则抛出InterruptedException

  • 如果已经有终态isDone()=true,则return this

  • 判断线程是否被中断Thread.interrupted(),如果被中断则抛出异常 throw new InterruptedException(toString());

  • 检查死锁 checkDeadLock();

  • 做synchronized (this)

    • 如果没有终态持续执行以下操作while (!isDone())
    • 增加等待者incWaiters();
    • 调用object.wait()
    • 减少等待者decWaiters();
  • return this

public Promise awaitUninterruptibly()

  • 语义:等待直到这个Future有终态,且不可被中断

  • 如果已经有终态isDone()=true,则return this

  • 检查死锁 checkDeadLock();

  • 做synchronized (this)

    • 如果没有终态持续执行以下操作while (!isDone())
    • 增加等待者incWaiters();
    • 调用object.wait(),捕获InterruptedException异常,且记录有没有被中断:interrupted = true;
    • 减少等待者decWaiters();
  • 如果interrupted = true;则恢复线程的被中断标志位 Thread.currentThread().interrupt();

  • return this

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

  • 语义:一个超时的wait,同时可以中断
  • return await0(unit.toNanos(timeout), true);

public boolean await(long timeoutMillis) throws InterruptedException

  • return await0(MILLISECONDS.toNanos(timeoutMillis), true);

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

public boolean awaitUninterruptibly(long timeoutMillis)

  • try { return await0(MILLISECONDS.toNanos(timeoutMillis), false); } catch (InterruptedException e) { // Should not be raised at all. throw new InternalError(); }

public Promise sync() throws InterruptedException

  • 语义:等待直到Future有终态,如果Future是失败的,那么会重抛把失败的原因
    1.     await();
      
    1. 如果失败重抛异常rethrowIfFailed();
    1. return this;

public Promise syncUninterruptibly()

    1.     awaitUninterruptibly();
      
    1. 如果失败重抛异常rethrowIfFailed();
    1. return this;

public V get() throws InterruptedException, ExecutionException

  • 判断是否有终态isDone0,如果没有终态则调用 await();
  • 如果result == SUCCESS || result == UNCANCELLABLE,则返回null
  • 获取异常原因 Throwable cause = cause0(result);
  • 如果cause,则返回result: if (cause == null) { return (V) result; }
  • 如果cause是CancellationException则抛出该异常, if (cause instanceof CancellationException) { throw (CancellationException) cause; }
  • 否则,则抛出ExecutionException: throw new ExecutionException(cause);

public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

  • 判断是否有终态isDone0,如果没有终态则调用await(timeout, unit),如果await返回false,则抛TimeoutException
  • 如果result == SUCCESS || result == UNCANCELLABLE,则返回null
  • 获取异常原因 Throwable cause = cause0(result);
  • 如果cause,则返回result: if (cause == null) { return (V) result; }
  • 如果cause是CancellationException则抛出该异常, if (cause instanceof CancellationException) { throw (CancellationException) cause; }
  • 否则,则抛出ExecutionException: throw new ExecutionException(cause);

public V getNow()

  • 如果是result instanceof CauseHolder || result == SUCCESS || result == UNCANCELLABLE,则return null,其他的情return result

核心私有方法

protected void checkDeadLock()

  • 获取EventExecutor不为null且它在EventLoop中e != null && e.inEventLoop()则抛异常throw new BlockingOperationException(toString());

private void incWaiters()

  • 检验this.waiters的大小,如果达到了Short.MAX_VALUE,则抛出异常throw new IllegalStateException("too many waiters: " + this);
  • ++waiters;

private void decWaiters()

  • --waiters;

private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException

  • 如果已经有终态isDone()=true,则return true

  • 如果等待时间<=0,timeoutNanos <= 0,则直接返回 return isDone();

  • 如果interruptable=true,且当前线程的中断标志位为true:interruptable && Thread.interrupted(),则抛异常:throw new InterruptedException(toString());

  • 校验死锁: checkDeadLock();

  • 做synchronized (this)

    • 如果没有终态持续且当前的等待时间>0执行以下操作while (!isDone() && waitTime > 0)

      • 增加等待者incWaiters();
      • 调用wait(long timeout, int nanos),捕获InterruptedException异常:如果可中断interruptable=true,则将InterruptedException抛出,否则记录曾经被中断interrupted = true;
      • 减少等待者decWaiters();
      • 判断是否有终态isDone,如果有终态了则返回ture,否则计算下还需要等待多久waitTime
    • 返回isDone();

    • finally块中:如果曾经被中断过,则再次将线程中断Thread.currentThread().interrupt();

private void rethrowIfFailed()

    1. Throwable cause = cause();
    1. if (cause == null) { return; }
  • PlatformDependent.throwException(cause);

    • 如果有Unsafe:hasUnsafe()则用Unsafe抛异常: UNSAFE.throwException(checkNotNull(cause, "cause"));
    • 否则就正常抛异常