How can I test that ConcurrentHashMap is truly thread-safe?

我只是一个虾纸丫 提交于 2019-12-10 10:33:15

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/8567495/how-can-i-test-that-concurrenthashmap-is-truly-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!