What is the use of ConcurrentHashMap in Java? What are its benefits? How does it work?
Sample code would be useful too.
What is the use of ConcurrentHashMap in Java? What are its benefits? How does
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The point is to provide an implementation of
HashMapthat is threadsafe. Multiple threads can read from and write to it without the chance of receiving out-of-date or corrupted data.ConcurrentHashMapprovides its own synchronization, so you do not have to synchronize accesses to it explicitly.Another feature of
ConcurrentHashMapis that it provides theputIfAbsentmethod, which will atomically add a mapping if the specified key does not exist. Consider the following code:This code is not threadsafe, because another thread could add a mapping for
"key"between the call tocontainsand the call toput. The correct implementation would be: