问题描述
只需学习更多有关线程和并发的知识,并考虑使用常规哈希表和ConcurrentHashMap。
Just learning more about threads and concurrency, and thought of playing around with a regular hashtable and a ConcurrentHashMap.
什么是测试并发性的好方法?这些哈希表?
What would be a good way to test for concurrency for these hashtables?
(显然哈希表将无法通过该测试)
(obviously the hash table will fail this test)
如果我还能以某种方式保持跟踪测试执行多少次读/写操作,以便更快地查看哪一个(ht或并发ht)。
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.
推荐答案
回答关于您如何测试它的最后编辑。这也涉及Hot Licks评论。实际上,您无法真正测试线程安全性,因为它是高度不确定性的,并且故障通常会持续很长时间。
This is an answer to your last edit about how you can test it. This also touches on Hot Licks comment. In practice you can't really test thread safety as it is highly non-deterministic and failures usually occur over long periods of time.
有一个。哪个放入
并带有多个线程的HashMap可能导致它进入无限循环。运行与此类似的代码
There is a nice race condition with a non-thread-safe HashMap. Which put
ing into the HashMap with multiple threads can cause it to go into an infinite loop. 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
这篇关于如何测试ConcurrentHashMap是真正的线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!