Java – how to verify ConcurrentHashMap is threadsafe

concurrencyjava

As the jdk doc said, ConcurrentHashMap is thread safe and it doesn't block multiple thread read. It is not necessary to doubt that since it was under many and restricted test. But I just curious how to tell and write code to verify that.

Edited: to be more precisely

  1. how to keep read consitent without read block
  2. does it return the latest view of data

Best Answer

To all practical purposes, you can't. You can run a number of successful tests numerous times, then without making a change, a test will fail. This is what makes testing multi-threading hard - it is not deterministic.

You may be able to test to an acceptable degree of certainty using statistical methods i.e. we ran 10^y randomized tests with no faults found- it is statistically probable that there are no defects.

You cannot run a test that guarantees thread safety, it has to be done by design and white box testing that the design has been implemented correctly.

As far as ConcurrentHashMap - if your vendor says something is thread safe, you can only decide, do I trust my vendor - or perhaps paraphrasing a great movie line "You've got to ask yourself one question: Do I feel lucky? Well, do ya, punk?" - and if you don't trust your vendor, I think maybe you have bigger problems.

EDIT: My background involves Life critical and Hard Real time (sub nanosecond) embedded systems. My questions is answered in the context of "Whats the worst that happens" being somewhat more important than "an unexplained software crash"......