Hashtable使用误区一例

在一个实现多线程并发的代码中,需要使用一个Map类型的容器来保存某一Socket上连接的用户列表.考虑到线程安全的问题,采用Hashtable是理所应当的选择.但以前错误的以为使用Hashtable了就确保了线程安全,因此仍然按照惯例使用如下的代码对容器内的值进行操作:
[code]
Collection keySet = clients.keyset();
Iterator it = keySet.iterator();
while(it.hasNext())
{
Key key = (Key)it.next();
Client client = (Client)clients.get(key);
.......
}
[/code]
但是系统在实际运行过程中,偶尔会出现漏掉某些client的情况.经过debug,问题定位到上面的代码片段.翻开Jsdk手册,发现对Hashtable的解释里如下一段话:
[quote]
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.
[/quote]
原来Hashtable本身虽然线程安全,但是对Hashtable返回的任何形式collection使用Iterator都是会快速失败的!也就是说这个Iterator并不能保证线程安全!!究竟为什么会这样,个人猜测是为了保证Iterator操作的一致性而做的折衷.将上述代码改成
[code]
Enumeration enu = clients.kes();
while(enu.hasMoreElements())
{
Key key = (Key)enu.nextElement();
Client client = (Client)clients.get(key);
.......
}
[/code]
后排除了这个bug.看来,还是得更仔细的研究jsdk了.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值