浏览 3523 次
锁定老帖子 主题:Hashtable使用误区一例
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2006-11-09
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了. 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |