科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道深入列表遍历问题,并分析spring和tomcat中观察者模式的实现

深入列表遍历问题,并分析spring和tomcat中观察者模式的实现

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

本文深入探索列表遍历的两种方式,然后探讨了spring和tomcat中如何遍历监听者。

作者:袁乐天 来源:CSDN 2008年3月19日

关键字: Tomcat Spring java

  • 评论
  • 分享微博
  • 分享邮件

列表的遍历有两种方式,一种是采用for循环,如下所示:

List list=new ArrayList();
for(int i=0;i<list.size();i++){
//...
}

还有一种是采用Iterator接口 ,如下所示:

Iterator ite=list.iterator();
while(ite.hasNext()){
//...
}

那么这两种方式有什么差别呢?答案是在顺序执行的程序中,他们没有差别;但是在并行程序中有差别。如果在遍历的过程中有另外一个线程修改了list,那么采用for循环其执行结果是不确定的,而采用Iterator会快速失败(fast-fail)并抛出ConcurrentModificationException。所以在通常情况下,优先使用Iterator遍历集合对象。

有时候我们需要在遍历过程中保证集合不被修改,这就需要对集合进行同步。

    synchronized(list){
        Iterator ite
=list.iterator();
        
while(ite.hasNext()){
         
//...
        }

    }


上面这种方式需要在遍历过程中完全锁住被访问的list对象,如果遍历过程耗时较长容易导致性能下降和死锁。所以有时可以采用临时拷贝的方法,在拷贝后的私有临时集合上执行遍历操作。

            Object[] snapshot;
            
synchronized (list) {
                snapshot 
= new Object[list.size()];
                
for (int i = 0; i < snapshot.length; ++i)
                    snapshot[i] 
= list.get(i);
            }

            
for (int i = 0; i < snapshot.length; ++i) {
                    //...
            }


下面考虑一个实际的例子,就是observer模式。一个目标对象有多个观察者,当目标状态发生变化时,它向各个观察者发出通知。下面是tomcat5中ContainerBase类的一个方法:

    public void fireContainerEvent(String type, Object data) {

        
if (listeners.size() < 1)
            
return;
        ContainerEvent event 
= new ContainerEvent(this, type, data);
        ContainerListener list[] 
= new ContainerListener[0];
        
synchronized (listeners) {
            list 
= (ContainerListener[]) listeners.toArray(list);
        }

        
for (int i = 0; i < list.length; i++)
            ((ContainerListener) list[i]).containerEvent(event);

    }

可见它采用的是临时拷贝的方法。
下面是spring中ApplicationEventMulticasterImpl类的一个方法:

    public void onApplicationEvent(ApplicationEvent e) {
        Iterator i 
= eventListeners.iterator();
        
while (i.hasNext()) {
            ApplicationListener l 
= (ApplicationListener) i.next();
            l.onApplicationEvent(e);
        }

    }

可见spring采用的是未同步的Iterator方法。

我认为Spring的写法是不恰当的。这涉及到服务器端应用和客户端应用异常处理方式的问题。对于客户端应用,完全可以采用不同步的Iterator方式。当异常发生时提示操作者是放弃操作,还是重试。但是对于服务器端应用,必须保证在遍历的过程中不发生异常。Spring作为一个通用的组件管理框架,当然不能假定其使用的场合。

 后记:java5中的java.util.concurrent包中的集合类,提供了另外一种形式的weakly-consistent iterator。它不同于传统的fast-fail Iterator。they promise to be thread safe, but don't promise whether you will see any updates made to the collection since the iterator was constructed (e.g., you might see an added element, or you might not).

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章