PromiseTask

287 阅读2分钟

1 类的继承体系

image.png

2 代码详情

这个地方netty和jdk有一些不一样,jdk的是FutureTask统一实现了Future和Runnable两个接口;

netty是DefaultPromise实现了Future的功能,PromiseTask又继承了DefaultPromise了,然后实现Runnable接口;

2.1 有两个内部类

2.1.1 Runnable的适配器

将Runnable适配成Callable。

private static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
 
    RunnableAdapter(Runnable task, T result) {
        this.task = task;
        this.result = result;
    }
 
    @Override
    public T call() {
        task.run();
        return result;
    }
 
    @Override
    public String toString() {
        return "Callable(task: " + task + ", result: " + result + ')';
    }
}

2.1.2 哨兵Runnable

private static class SentinelRunnable implements Runnable {
    private final String name;
 
    SentinelRunnable(String name) {
        this.name = name;
    }
 
    @Override
    public void run() { } // no-op
 
    @Override
    public String toString() {
        return name;
    }
}

2.2.3 私有变量和构造函数

// Strictly of type Callable<V> or Runnable
private Object task;
 
PromiseTask(EventExecutor executor, Runnable runnable, V result) {
    super(executor);
    task = result == null ? runnable : new RunnableAdapter<V>(runnable, result);
}
 
PromiseTask(EventExecutor executor, Runnable runnable) {
    super(executor);
    task = runnable;
}
 
PromiseTask(EventExecutor executor, Callable<V> callable) {
    super(executor);
    task = callable;
}

其中的task是一个Callable或者Runnable,构造函数的EventExecutor executor入参给父类的DefaultPromise#executor变量赋值。

2.2 共有方法

2.2.1 run方法

@Override
public void run() {
    try {
        if (setUncancellableInternal()) {
            V result = runTask();
            setSuccessInternal(result);
        }
    } catch (Throwable e) {
        setFailureInternal(e);
    }
}

setUncancellableInternal调用的父类DefaultPromised的setUncancellable方法,将状态更改为不可取消的,这个方法只有一种情况会更新失败,那就是此时的状态为以取消,如果状态是已取消,那么run方法则退出。

之后去跑任务runTask():

@SuppressWarnings("unchecked")
V runTask() throws Throwable {
    final Object task = this.task;
    if (task instanceof Callable) {
        return ((Callable<V>) task).call();
    }
    ((Runnable) task).run();
    return null;
}

如果runTask方法抛出异常了,那么则会调用setFailureInternal(e):

protected final Promise<V> setFailureInternal(Throwable cause) {
    super.setFailure(cause);
    clearTaskAfterCompletion(true, FAILED);
    return this;
}

首先调用父类[DefaultPromise]的setFailure方法将状态置为失败;

clearTaskAfterCompletion(true, FAILED)顾名思义是请任务清掉:
private boolean clearTaskAfterCompletion(boolean done, Runnable result) {
    if (done) {
        // The only time where it might be possible for the sentinel task
        // to be called is in the case of a periodic ScheduledFutureTask,
        // in which case it's a benign race with cancellation and the (null)
        // return value is not used.
        task = result;
    }
    return done;
}
 
 
private static final Runnable FAILED = new SentinelRunnable("FAILED");

如果runTask成功,则用返回值去调setSuccessInternal(result);

protected final Promise<V> setSuccessInternal(V result) {
    super.setSuccess(result);
    clearTaskAfterCompletion(true, COMPLETED);
    return this;
}
private static final Runnable COMPLETED = new SentinelRunnable("COMPLETED");

先调用父类DefaultPromised的setSuccess方法将状态置为成功;

将任务清掉并设置为COMPLETED。

2.2.2 setFailure方法

@Override public final Promise<V> setFailure(Throwable cause) {     throw new IllegalStateException(); }

覆盖setFailure方法,不允许这个方法被调用。

2.2.3 tryFailure方法

@Override public final boolean tryFailure(Throwable cause) {     return false; }

这个方法也直接return false。

2.2.4 setSuccess方法

@Override public final Promise<V> setSuccess(V result) {     throw new IllegalStateException(); }

覆盖setSuccess不允许其调用。

2.2.5 trySuccess方法

@Override public final boolean trySuccess(V result) {     return false; }

这个方法也直接return false。

2.2.6 cancel方法

@Override public boolean cancel(boolean mayInterruptIfRunning) {   
    return clearTaskAfterCompletion(super.cancel(mayInterruptIfRunning), CANCELLED); 
}
private static final Runnable CANCELLED = new SentinelRunnable("CANCELLED");

调用父类DefaultPromise的cancel方法,然后在将task赋值成CANCELLED。

3 总结

PromiseTask和jdk的FutureTask在功能上一样的,可以run,可以get,可以取消,但是不可以setSuccess 和setFailure。