如何测试 ConcurrentHashMap 是否真正线程安全?

发布于 2024-12-22 09:18:44 字数 164 浏览 2 评论 0原文

只是了解有关线程和并发的更多信息,并考虑使用常规哈希表和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2024-12-29 09:18:44

这是对您上次编辑有关如何测试它的答案。这也涉及到 Hot Licks 的评论。在实践中,您无法真正测试线程安全性,因为它具有高度不确定性,并且故障通常会在很长一段时间内发生。

有一个非线程的很好的竞争条件安全的哈希映射。将多个线程放入 HashMap 中可能会导致其进入无限循环。运行类似于此

    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

注释的代码,我使用的可能是因为您可以多次运行此测试并且不会进入无限循环,但我已经完成了此测试并且可以轻松地使循环发生

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 puting 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文