[英]How can I test that ConcurrentHashMap is truly thread-safe?
Just learning more about threads and concurrency, and thought of playing around with a regular hashtable and a ConcurrentHashMap. 只是学习更多关于线程和并发性的知识,并考虑使用常规哈希表和ConcurrentHashMap。
What would be a good way to test for concurrency for these hashtables? 测试这些哈希表的并发性的好方法是什么?
(obviously the hash table will fail this test) (显然哈希表会通过此测试)
It would be cool if I could also somehow keep track of how many reads/writes the test performs to see which one (ht or conccurrent ht) faster. 如果我还能以某种方式跟踪测试执行多少读/写以更快地查看哪一个(ht或conccurrent ht),那将会很酷。
This is an answer to your last edit about how you can test it. 这是您上次编辑如何测试它的答案。 This also touches on Hot Licks comment.
这也涉及Hot Licks的评论。 In practice you can't really test thread safety as it is highly non-deterministic and failures usually occur over long periods of time.
在实践中,您无法真正测试线程安全性,因为它非常不确定,故障通常会在很长一段时间内发生。
There is a nice race condition with a non-thread-safe HashMap. 有一个非线程安全的HashMap有一个很好的竞争条件 。 Which
put
ing into the HashMap with multiple threads can cause it to go into an infinite loop. 这
put
荷兰国际集团与多线程HashMap的会导致它进入无限循环。 Run code similar to this 运行与此类似的代码
ExecutorService e = Executors.newFixedThreadPool(5);
public void test(final Map<Object,Object> map){
for(int i =0; i < 5000; i++){
e.submit(new Runnable(){
public void run(){
map.put(new Object(),new Object());
}
});
}
}
test(new HashMap<Object,Object>()); //will probably go into an infinite loop
test(new ConcurrentHashMap<Object,Object>()); //will *never* go into an infinite loop
Note I used probably because you can run this test a number of times and not go into an infinite loop, but I have done this test and can easily get the loop to occur 注意我之所以使用可能是因为你可以多次运行这个测试而不是进入无限循环,但是我已经完成了这个测试并且很容易让循环发生
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.