如何测试 ConcurrentHashMap 是否真正线程安全?
只是了解有关线程和并发的更多信息,并考虑使用常规哈希表和 ConcurrentHashMap。
测试这些哈希表并发性的好方法是什么?
(显然哈希表将无法通过此测试)
如果我还可以以某种方式跟踪测试执行的读/写次数以查看哪一个(ht 或并发 ht)更快,那就太酷了。
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是对您上次编辑有关如何测试它的答案。这也涉及到 Hot Licks 的评论。在实践中,您无法真正测试线程安全性,因为它具有高度不确定性,并且故障通常会在很长一段时间内发生。
有一个非线程的很好的竞争条件安全的哈希映射。将多个线程放入 HashMap 中可能会导致其进入无限循环。运行类似于此
注释的代码,我使用的可能是因为您可以多次运行此测试并且不会进入无限循环,但我已经完成了此测试并且可以轻松地使循环发生
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.
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 thisNote 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