MINA探究之IoFuture

本文介绍IoFuture及其监听器IoFutureListener的工作原理,解释如何通过这些组件实现在Apache MINA框架中对IoSession的异步IO操作完成进行监听。文章还探讨了IoFuture的四个子接口及DefaultIoFuture实现类的关键属性。

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

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 这个函数一样去解决处理了。研究研究源码是王道,这里只是一个开始,有兴趣可以多读几遍相关源码继续深入了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值