Netty异步编程之Future和Promise

本文介绍了Netty中的异步编程机制,重点讲解了Future和Promise的概念与功能。Future作为异步操作的结果表示,提供了获取结果、判断完成状态和尝试取消操作的能力。Netty的ChannelFuture专用于I/O操作,具有未完成和已完成两种状态。Promise则提供了可变状态,允许设置操作的成功或失败。DefaultPromise和DefaultChannelPromise是其实现,包含具体的状态管理和回调操作。Netty推荐通过添加监听器来处理I/O操作结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty 源码中大量使用了异步编程,从代码实现角度看就是大量使用了线程池和 Future。并在Java自带Future的基础上,增加了Promise机制。这两者的目的都是使异步编程更加方便使用。在阅读源码之前,我们需要对Future的机制有很清楚的认识。

1.Future功能

Future最早来自JDK的java.util.concurrent.Future,它用于代表异步操作的结果,相关API如下:

public interface Future<V> {
   
   
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

可以通过get方法获取操作结果,如果操作尚未完成,则会同步阻塞当前调用的线程;如果不允许阻塞太长时间或无限期阻塞,可以通过待超时时间的get方法获取结果;如果到达超时时间操作仍未完成,则抛出TimeoutException。
通过isDone()方法可以判断当前的异步操作是否完成,如果完成无论成功与否,都返回true,否则返回false。
通过cancel可以尝试取消异步操作,它的结果是未知的,如果操作以及完成,或者发生其他未知的原因拒绝取消,取消操作将会失败。
Netty中的Future在JDK 中java.util.concurrent.Future基础上增加一些功能:

public interface Future<V> extends java.util.concurrent.Future<V> {
   
   

    /**
     * Returns {@code true} if and only if the I/O operation was completed
     * successfully.
     */
    boolean isSuccess();

    /**
     * returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}.
     */
    boolean isCancellable();

    /**
     * Returns the cause of the failed I/O operation if the I/O operation has
     * failed.
     *
     * @return the cause of the failure.
     *         {@code null} if succeeded or this future is not
     *         completed yet.
     */
    Throwable cause();

    /**
     * Adds the specified listener to this future.  The
     * specified listener is notified when this future is
     * {@linkplain #isDone() done}.  If this future is already
     * completed, the specified listener is notified immediately.
     */
    Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);

    /**
     * Adds the specified listeners to this future.  The
     * specified listeners are notified when this future is
     * {@linkplain #isDone() done}.  If this future is already
     * completed, the specified listeners are notified immediately.
     */
    Future<V> addListeners(GenericFutureListener<? extends Future
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值