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

纵然是瞬间 提交于 2019-12-06 06:55:17
John Vint

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

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