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