Future模式,探讨mina中的Iofuture

简介: 2010-02-09 Future模式 文章分类:Java编程 在mina中有各种各样的future,如果不知道这背后的future模式,那么对mina的理解就不可能深入。 什么是future模式呢? 经常有一个线程需要得到另个一线程的计算结果,我们常用的是Future异步模式来加以解决。
2010 - 02 - 09

Future模式

文章分类:Java编程

在mina中有各种各样的future,如果不知道这背后的future模式,那么对mina的理解就不可能深入。

什么是future模式呢?

经常有一个线程需要得到另个一线程的计算结果,我们常用的是Future异步模式来加以解决。
Future顾名思意,有点像期货市场的“期权”,是“对未来的一种凭证”,例如当我们买了某个房地产开发商的期房,交钱之后,开发商会给我们一个凭证(期权),这个凭证告诉我们等明年某个时候拿这个凭证就可以拿到我们所需要的房子,但是现在房子还没建好。市场上之所以有“期货”,也正由于有这种需求,才有这种供给。

 

这种应用在GUI上用的比较多,在设计模式中一般称为“虚拟代理模式 ”。

Future大至的交互图:

 

详情:http://java1995.cn/blog/item/114

 

2010 - 02 - 22

探讨mina中的Iofuture

文章分类:Java编程

先了解下future是个什么东东?

Future模式

future pattern

future pattern改进

以上三篇可以让你明白什么是future。

现在再来看mina中的iofuture

IoFuture.png

我们常常发现有些东西只有一部分是公共的,其他部分是个性的,于是我们把公共的东西单独抽象成一个超接口(比如这里的IoFuture),其他个性的东西,是在公共的基础上增加个性的东西,所以public interface ConnectFuture extends IoFuture;public interface ReadFuture extends IoFuture等等;同时,我们公共的东西可以公共的实现public class DefaultIoFuture implents IoFuture。然后个性的东西,在公共实现的基础上完成(重用:可以选择继承,或组合),于是public class ConnetFuture extends DefaultIoFuture implents ConnectFuture,其中extends DefaultIoFuture体现了用继承的方式重用公共的操作,implments ConnectFuture体现了在公共的基础上再去实现个性的东西。

 

如果要看Future机制的话,我们只需要了解DefaultIoFuture这个公共操作类。我们首先看下IoFuture描述了哪些功能需求:

(1)boolean isReady     判断“真实东西”是否准备完毕;

(2)await/awaitUninterruptibly  表示如果客户比较着急(可能在真实东西准备好之前就想提货),程序会阻塞客户,这里相对我前面的future pattern 中提供的措施要丰富些,用户可以选择长期阻塞await【内部最终实现是lock.wait()】,或者在一定时间内阻塞await(long timeout)【内部最终实现是lock.wait(timeout)】;

(3)addListener/removeListerner  这个东西和Future模式没有什么关系,只是个观察者模式。

(4)future pattern 中说了还需要回答一个问题是:  当真实的数据准备好的时候,真实数据怎么通知这个Future说数据好了,在DefaultIoFuture中有一个protected void setValue(object newVaule)方法,以供提供真实数据的人调用。(这里顺便提下刚才的addListener/removeListener:当Future对应的真实数据准备好时,方法setValue会被调用,那么Future接收到这个通知真实数据OK时,利用观察者模式把这个消息再向它的观察着进行广播下。)

对future有了理解,再来阅读mina的源码就相当简单明了。

在mina中有两段重点注意下的代码,值得学习。

DefaultIoFuture中:

一是等待代码

 /**     * Wait for the Future to be ready. If the requested delay is 0 or      * negative, this method immediately returns the value of the      * 'ready' flag.      * Every 5 second, the wait will be suspended to be able to check if      * there is a deadlock or not.     *      * @param timeoutMillis The delay we will wait for the Future to be ready     * @param interruptable Tells if the wait can be interrupted or not     * @return <code>true</code> if the Future is ready     * @throws InterruptedException If the thread has been interrupted     * when it's not allowed.     */    private boolean await0(long timeoutMillis, boolean interruptable) throws InterruptedException {        long endTime = System.currentTimeMillis() + timeoutMillis;        synchronized (lock) {            if (ready) {                return ready;            } else if (timeoutMillis <= 0) {                return ready;            }            waiters++;            try {                for (;;) {                    try {                        long timeOut = Math.min(timeoutMillis, DEAD_LOCK_CHECK_INTERVAL);                        lock.wait(timeOut);                    } catch (InterruptedException e) {                        if (interruptable) {                            throw e;                        }                    }                    if (ready) {                        return true;                    } else {                        if (endTime < System.currentTimeMillis()) {                            return ready;                        }                    }                }            } finally {                waiters--;                if (!ready) {                    checkDeadLock();                }            }        }    }

 

二是检查死锁

/**     *      * TODO checkDeadLock.     *     */    private void checkDeadLock() {        // Only read / write / connect / write future can cause dead lock.         if (!(this instanceof CloseFuture || this instanceof WriteFuture ||              this instanceof ReadFuture || this instanceof ConnectFuture)) {            return;        }                // Get the current thread stackTrace.         // Using Thread.currentThread().getStackTrace() is the best solution,        // even if slightly less efficient than doing a new Exception().getStackTrace(),        // as internally, it does exactly the same thing. The advantage of using        // this solution is that we may benefit some improvement with some        // future versions of Java.        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();        // Simple and quick check.        for (StackTraceElement s: stackTrace) {            if (AbstractPollingIoProcessor.class.getName().equals(s.getClassName())) {                IllegalStateException e = new IllegalStateException( "t" );                e.getStackTrace();                throw new IllegalStateException(                    "DEAD LOCK: " + IoFuture.class.getSimpleName() +                    ".await() was invoked from an I/O processor thread.  " +                    "Please use " + IoFutureListener.class.getSimpleName() +                    " or configure a proper thread model alternatively.");            }        }        // And then more precisely.        for (StackTraceElement s: stackTrace) {            try {                Class<?> cls = DefaultIoFuture.class.getClassLoader().loadClass(s.getClassName());                if (IoProcessor.class.isAssignableFrom(cls)) {                    throw new IllegalStateException(                        "DEAD LOCK: " + IoFuture.class.getSimpleName() +                        ".await() was invoked from an I/O processor thread.  " +                        "Please use " + IoFutureListener.class.getSimpleName() +                        " or configure a proper thread model alternatively.");                }            } catch (Exception cnfe) {                // Ignore            }        }    }
相关文章
|
6月前
04RPC - netty中handler的执行顺序
04RPC - netty中handler的执行顺序
46 0
|
10月前
|
设计模式 Java API
【JUC基础】15. Future模式
Future 模式是多线程开发中非常常见的一种设计模式,它的核心思想是异步调用。当我们需要调用一个函数方法时,如果这个函数执行得很慢,那么我们就要进行等待。但有时候,我们可能并不急着要结果。因此,我们可以让被调者立即返回,让它在后台慢慢处理这个请求。对于调用者来说,则可以先处理一些其他任务,在真正需要数据的场合再去尝试获得需要的数据。
113 0
【JUC基础】15. Future模式
|
11月前
|
存储 Java
Netty网络编程(四):Event、Handler和Pipeline
Netty网络编程(四):Event、Handler和Pipeline
81 0
|
11月前
|
前端开发 算法 Java
Netty组件Future、Promise、Handler、Pipline、ByteBuf
Netty组件Future、Promise、Handler、Pipline、ByteBuf
53 0
|
缓存 移动开发 网络协议
第 8 章 Netty 编解码器和 Handler 调用机制
第 8 章 Netty 编解码器和 Handler 调用机制
137 0
|
前端开发 Java 数据处理
【Netty】Netty 异步任务模型 及 Future-Listener 机制
【Netty】Netty 异步任务模型 及 Future-Listener 机制
543 0
【Netty】Netty 异步任务模型 及 Future-Listener 机制
|
调度 数据库
【Netty】 异步任务调度 ( TaskQueue | ScheduleTaskQueue | SocketChannel 管理 )
【Netty】 异步任务调度 ( TaskQueue | ScheduleTaskQueue | SocketChannel 管理 )
459 0
|
并行计算 API
|
网络协议 算法
小六六学Netty系列之编解码器和handler的调用机制(下)
前言 文本已收录至我的GitHub仓库,欢迎Star:github.com/bin39232820… 种一棵树最好的时间是十年前,其次是现在
132 0
|
存储 编解码 网络协议
小六六学Netty系列之编解码器和handler的调用机制(上)
前言 文本已收录至我的GitHub仓库,欢迎Star:github.com/bin39232820… 种一棵树最好的时间是十年前,其次是现在
206 0