Netty-12 Future和Promise

一、Future

io.netty.util.concurrent.Future继承自java.util.concurrent.Future,用来表示异步操作的结果。

(一)jdk的Future

定义了如下几个操作:
在这里插入图片描述

  • cancel:取消操作
  • get:获取操作的结果
  • get(long,TimeUnit):获取操作结果,有超时时间,超过报错;
  • isCancelled:是否已经取消了,如果取消了,返回true;
  • isDone:完成了返回true;

(二)AbstractFuture

AbstractFuture是对Futrue的一个抽象实现,实现了get方法,如下:

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

    @Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (await(timeout, unit)) {
            Throwable cause = cause();
            if (cause == null) {
                return getNow();
            }
            if (cause instanceof CancellationException) {
                throw (CancellationException) cause;
            }
            throw new ExecutionException(cause);
        }
        throw new TimeoutException();
    }

可以看到,利用了await一直等待(超时的设置有等待事件),当操作结束后,会调用notify(),程序向下执行。

(三)Netty的Future

Netty的Future在jdk的基础了,又扩展出了一些方法,如下:
在这里插入图片描述
其中比较重要的是addListener方法和removeListener方法,我们可以通过这两个方法来添加监听的事件。当I/O操作结束之后,会调用我们添加进去的GenericFutureListener,所以,我们可以通过这种方式来获取操作的结果

(四)ChannelFuture

在Netty中,几乎所以的I/O操作都是异步的,也就是说,所有的操作都会立即返回,而不是像BIO那样阻塞等待结果,那么,结果如果返回就成了一个问题,ChannelFuture就是为了解决这个问题。
ChannelFutue最主要的实现类有:SucceededChannelFuture和FailedChannelFuture,实现都比较简单。

二、Promise

promise是可写的Future,Future自身没有写操作相关的接口,Netty通过Promise对Future进行扩展,用于设置I/O操作的结果。
在Netty发起I/O操作的时候,会创建一个Promise,如在调用ChannelHandlerContext的write方法的时候。

(一)DefaultPromise

Promise的默认实现是DefaultPromise,实现了setSuccess等方法。成功的时候,会触发listener,然后,被返回给用户。

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

猜你喜欢

转载自blog.csdn.net/mail_liuxing/article/details/91365742
今日推荐