Netty Promise

Netty Promise

demo

package com.zc.demo.netty;

import io.netty.util.concurrent.*;

public class T01DefaultPromise {

    public static void main(String[] args) {
        // 构造线程池
        EventExecutor executor = new DefaultEventExecutor();

        // 创建 DefaultPromise 实例
        final Promise promise = new DefaultPromise(executor);

        // 下面给这个 promise 添加两个 listener
        promise.addListener(new GenericFutureListener<Future<Integer>>() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("任务结束,结果:" + future.get());
                } else {
                    System.out.println("任务失败,异常:" + future.cause());
                }
            }
        }).addListener(new GenericFutureListener<Future<Integer>>() {
            @Override
            public void operationComplete(Future future) throws Exception {
                System.out.println("任务结束,balabala...");
            }
        });

        // 提交任务到线程池,1 秒后执行结束,设置执行 promise 的结果
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                // 设置 promise 的结果
                // promise.setFailure(new RuntimeException());
                // 具体的任务不一定就要在这个 executor 中被执行。
                // 任务结束以后,需要调用 promise.setSuccess(result) 或失败 作为通知
                System.out.println("before promise.setSucess()");
                promise.setSuccess(123456);
            }
        });

        try {
            // main 线程阻塞等待执行结果
            promise.sync();
            System.out.println("main 线程从 promise.sync() 阻塞中返回");
        } catch (InterruptedException e) {

        }
    }
}

Promise 接口

Promise 接口继承自 Future 接口, 在 Future 基础上提供了设置处理结果的功能.

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

    /** 标记该 future 成功及设置其执行结果,并且会通知所有的 listeners
     */
    Promise<V> setSuccess(V result);

    /** 和 setSuccess 方法一样,只不过如果失败,它不抛异常,返回 false
     */
    boolean trySuccess(V result);

    /** 标记该 future 失败,及其失败原因. 失败会抛异常
     */
    Promise<V> setFailure(Throwable cause);

    /** 标记该 future 失败,及其失败原因. 不抛异常
     */
    boolean tryFailure(Throwable cause);

    /** 标记该 future 不可以被取消
     */
    boolean setUncancellable();
    // ...

}

DefaultPromise

DefaultPromise 通过 CAS 操作来进行更新执行结果的操作.

promise.setSuccess() 设置结果

通过 cas 操作设置 objResult, 设置成功后
调用 checkNotifyWaiters 判断 waiter 计数
执行 listener 的回调方法
@Override
public Promise<V> setSuccess(V result) {
    if (setSuccess0(result)) { // 对操作结果进行判断
        return this;
    }
    throw new IllegalStateException("complete already:" + this);
}

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

private static final AtomicReferenceFieldUpdater<DefaultPromise, Object> RESULT_UPDATER =
            AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class, Object.class, "result");// result 字段由使用 RESULT_UPDATER 更新

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 boolean setValue0(Object objResult) {
    if (RESULT_UPDATER.compareAndSet(this, null, objResult) ||
        RESULT_UPDATER.compareAndSet(this, UNCANCELLABLE, objResult)) { // 设置值
        if (checkNotifyWaiters()) {
            notifyListeners(); // 执行 listener 的回调方法
        }
        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();
        }
    });
}

AbstractFuture.get() 获取结果

根据 result 结果判断是否要等待.
若完成了, 则直接返回 promise,getNow() 从 promise 中取出设置的 result 并返回.
若未完成
    响应中断
    校验死锁
同步判断若未完成, 则增加 waiter 计数, wait() 等待, 唤醒后再减少 waiter 计数

future.get()

public V get() throws InterruptedException, ExecutionException { //
    await();// 阻塞直到异步操作完成, 当 I/O 操作完成后会被 notify()

    Throwable cause = cause();
    if (cause == null) {
        return getNow();// 成功则返回结果. 从 promise 中取出设置的 result 并返回
    }
    if (cause instanceof CancellationException) {// 由用户取消
        throw (CancellationException) cause;
    }
    throw new ExecutionException(cause);// 失败抛出异常
}

DefaultPromise.await()

public Promise<V> await() throws InterruptedException {
    if (isDone()) {
        return this;
    }

    if (Thread.interrupted()) { // 响应中断
        throw new InterruptedException(toString());
    }

    checkDeadLock();

    synchronized (this) {
        while (!isDone()) {
            incWaiters(); // 增加 waiter 计数
            try {
                wait(); // 等待
            } finally {
                decWaiters(); // 减少 waiter 计数
            }
        }
    }
    return this;
}

private static boolean isDone0(Object result) {
    return result != null && result != UNCANCELLABLE; // 结果不为 null 且 不为 UNCANCELLABLE
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FlyingZCC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值