I have a thread (A) that has functionality to maintain a Collection (probably a HashMap) through two methods. One adds an object, the other takes away one. However, it doesn’t. Instead, a different thread (B) calls these whenever necessary.
The first thread (A) still needs to search the Collection quite a bit though. How do I do this the safest way? I know I could mark the Collection volatile, but the java tutorials still tells me I could be getting memory inconsistency errors.
I am also aware that some Collections are thread-safe, but I need the mapping of a HashMap. So finally here is my question, now that you’re aware of the status-quo:
How do I make this operation completely thread-safe, the easiest way?
EDIT: My immidiate thoughts is to make both methods synchronized, as well as everywhere I want to look-up from thread (A). Problem is that it can be hundreds of times.
I would like to just make it volatile, but this specific passage makes me nervous:
“Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors.”
What is this? How does it even happen? How does one avoid it? Would that happen in my scenario? Most important of all, how can these errors even exist if volatile establishes a happens-before with any access to that field?