简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM