5.3 - FutureListener
Created by : Mr Dk.
2021 / 02 / 22 13:12
Ningbo, Zhejiang, China
GenericFutureListener
定义接口监听 Future
的执行结果。当监听器被注册到 Future
上后,Future
的执行结果会在执行完成后通知监听器。该接口的定义继承自 JDK 原生的 EventListener
,并且只定义了一个函数。
/**
* Listens to the result of a {@link Future}. The result of the asynchronous operation is notified once this listener
* is added by calling {@link Future#addListener(GenericFutureListener)}.
*/
public interface GenericFutureListener<F extends Future<?>> extends EventListener {
/**
* Invoked when the operation associated with the {@link Future} has been completed.
*
* @param future the source {@link Future} which called this callback
*/
void operationComplete(F future) throws Exception;
}
ChannelFutureListener
继承自 GenericFutureListener
,定义了几个监听器实现。operationComplete()
会直接被一个 I/O 线程回调,所以应当快速返回。如果需要执行一些耗时操作,应当把操作放在线程池的另一个线程中。
Definition
/**
* Listens to the result of a {@link ChannelFuture}. The result of the
* asynchronous {@link Channel} I/O operation is notified once this listener
* is added by calling {@link ChannelFuture#addListener(GenericFutureListener)}.
*
* <h3>Return the control to the caller quickly</h3>
*
* {@link #operationComplete(Future)} is directly called by an I/O
* thread. Therefore, performing a time consuming task or a blocking operation
* in the handler method can cause an unexpected pause during I/O. If you need
* to perform a blocking operation on I/O completion, try to execute the
* operation in a different thread using a thread pool.
*/
public interface ChannelFutureListener extends GenericFutureListener<ChannelFuture> {
}
Close
监听器实现。在 Channel
事件完成时关闭 Channel
。
/**
* A {@link ChannelFutureListener} that closes the {@link Channel} which is
* associated with the specified {@link ChannelFuture}.
*/
ChannelFutureListener CLOSE = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
future.channel().close();
}
};
Close On Failure
监听器实现。在 Channel
事件发生异常时关闭 Channel
。
/**
* A {@link ChannelFutureListener} that closes the {@link Channel} when the
* operation ended up with a failure or cancellation rather than a success.
*/
ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
future.channel().close();
}
}
};
Fire Exception On Failure
监听器实现。在 Channel
事件发生异常时,将 Throwable
对象传播到 ChannelPipeline
中。
/**
* A {@link ChannelFutureListener} that forwards the {@link Throwable} of the {@link ChannelFuture} into the
* {@link ChannelPipeline}. This mimics the old behavior of Netty 3.
*/
ChannelFutureListener FIRE_EXCEPTION_ON_FAILURE = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
future.channel().pipeline().fireExceptionCaught(future.cause());
}
}
};