I want to pass a pre-built Map to multiple threads that are going to only read the values from the Map simultaneously. Do I need to worry about concurrent access and use the ConcurrentHashMap instead of HashMap in this case?
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.
You still need to make sure that there is a “happens-before” relationship between the thread that creates and initializes the Map, and the threads that subsequently read it. If there is no such relationship, it is theoretically possible for the reading threads to see stale data.
If you create and populate the Map in the thread that starts the other threads … before it does this … you should be fine.
Another simple way to ensure safety is to do something like this:
Both of these will result in a “happens-before” relationship between the creation / initialization, and each thread’s first use of the Map.
You could also declare
mapin the above to bevolatile, but is likely to cause more cache flushes than strictly need to occur; i.e. you’ll take a small performance hit.