在一个实现多线程并发的代码中,需要使用一个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了.
分享到:
- 2006-11-09 03:48
- 浏览 2772
- 评论(0)
- 论坛回复 / 浏览 (0 / 3506)
- 查看更多
相关推荐
HashTable源码
Hashtable的基本用法,遍历等操作
WinFormHashTable最简单用法,.net hashtable ,hashtable ,hashtable用法
使用哈希表Hashtable填充ListBox
自己写的json字符串转hashtable,或者把hashtable转为json字符
使用哈希表的经典例子 使用哈希表的经典例子 使用哈希表的经典例子 使用哈希表的经典例子
哈市table的使用完整总结,赌约学习很有帮户的啊
Hashtable是Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中keyvalue键值对均为object类型,...
C# .net HashTable
一个用javascript写的hashtable类
利用asp.net遍历hashtable中的值
记得刚毕业那会准备面试,看过不少面试题,里面有个说出HashMap和HashTable不同的题目,我那会面试的时候也遇到不少次这个问题,还隐约记得当时的回答是这样的: HashTable是比较旧的版本;HashTable是线程安全的,...
c#通讯录hashtable
hashtable和hashmap的区别
Hashtable存储数据例子,希望大家多多指教
java Hashtable的泛型化 java Hashtable的泛型化 java Hashtable的泛型化
HashTable 常用操作
C/C++语言 hashtable代码 .c文件 适用于linux ubuntu unix等平台 terminal中操作
hashMap和hashTable的区别,大家可以下载学习学习。
该文档实现了Hashtable在C#中的常用的函数