`
floating
  • 浏览: 80482 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

Hashtable使用误区一例

阅读更多
在一个实现多线程并发的代码中,需要使用一个Map类型的容器来保存某一Socket上连接的用户列表.考虑到线程安全的问题,采用Hashtable是理所应当的选择.但以前错误的以为使用Hashtable了就确保了线程安全,因此仍然按照惯例使用如下的代码对容器内的值进行操作:
        Collection keySet = clients.keyset();
        Iterator it = keySet.iterator();
        while(it.hasNext())
        {
            Key key = (Key)it.next();
            Client client = (Client)clients.get(key);
            .......    
        }

但是系统在实际运行过程中,偶尔会出现漏掉某些client的情况.经过debug,问题定位到上面的代码片段.翻开Jsdk手册,发现对Hashtable的解释里如下一段话:
引用

The Iterators returned by the iterator and listIterator methods of the Collections returned by all of Hashtable's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and values methods are not fail-fast.

原来Hashtable本身虽然线程安全,但是对Hashtable返回的任何形式collection使用Iterator都是会快速失败的!也就是说这个Iterator并不能保证线程安全!!究竟为什么会这样,个人猜测是为了保证Iterator操作的一致性而做的折衷.将上述代码改成
	Enumeration enu = clients.kes();
        while(enu.hasMoreElements())
        {
            Key key = (Key)enu.nextElement();
            Client client = (Client)clients.get(key);
            .......    
        }

后排除了这个bug.看来,还是得更仔细的研究jsdk了.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics