IoFuture可以监听到针对一个特定的IoSession的异步IO操作完成的,具体通过加入一个IoFutureListener的监听器来实现。这个Future和其他的Future没什么两样,无非是异步监听,等待时间完成然后获得IoSession,针对这些功能有一些方法。
而这个IoFutureListenner通过继承EventListene这个空接口,在其Listtenner接口中实现了一个close的静态对象来完成operationComplete事件,具体可以参见如下源码:
/**
* Something interested in being notified when the completion
* of an asynchronous I/O operation : {@link IoFuture}.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface IoFutureListener<F extends IoFuture> extends EventListener {
/**
* An {@link IoFutureListener} that closes the {@link IoSession} which is
* associated with the specified {@link IoFuture}.
*/
static IoFutureListener<IoFuture> CLOSE = new IoFutureListener<IoFuture>() {
public void operationComplete(IoFuture future) {
future.getSession().close(true);
}
};
/**
* Invoked when the operation associated with the {@link IoFuture}
* has been completed even if you add the listener after the completion.
*
* @param future The source {@link IoFuture} which called this
* callback.
*/
void operationComplete(F future);
}
IoFuture包括四个子接口:分别是ConnectFuture ReadFuture WriteFuture CloseFuture。里面方法大同小异,这里就不一一举出。有兴趣的话可以直接参看源码。 针对每一个接口都有默认的实现类。我们来看一下DefaultIoFuture这个实现类。这个类一些私有属性如下:
private static final long DEAD_LOCK_CHECK_INTERVAL = 5000L;
/** The associated session */
private final IoSession session;
/** A lock used by the wait() method */
private final Object lock;
private IoFutureListener<?> firstListener;
private List<IoFutureListener<?>> otherListeners;
private Object result;
private boolean ready;
private int waiters;
其中值得关注的就是session和lock了,session是用来传递数据的了,这里用了final修饰,可以看到一个异步任务之后这个session引用就唯一了。其他session的详细情况关注后续的IoSession篇吧,呵呵。至于lock,还是那个lock,访问一些资源如 firstListener otherListeners等,针对不同的修改操作,在合适的方法位置加上锁就好了。 不过对象锁慎用啦,一定要留意避免死锁的问题,如果可能遇到的话,
那就checkDeadLock 这个函数一样去解决处理了。研究研究源码是王道,这里只是一个开始,有兴趣可以多读几遍相关源码继续深入了。