Forums Register Login

HashMap

+Pie Number of slices to send: Send
Hello,

I have a class which uses HashMap internally to store its data. I have 3 methods in the class - add(), get() and exists(). If this class were to be accessed from a multi-threading environment, should I synchronize all 3 methods?
+Pie Number of slices to send: Send
Yes.

The basic rule is that any time you have shared data, all access to that data must be protected.
+Pie Number of slices to send: Send
Thank you, Jeff. So, is the reasoning behind this the fact that a thread could add an object to the map at the same time another thread is using the exists() method?
+Pie Number of slices to send: Send
That's one scenario that could cause problems, yes. But really any case where 2 or more threads are accessing the shared data and at least one of them is writing it is a potential problem.
+Pie Number of slices to send: Send
Thank you.
Clowns were never meant to be THAT big! We must destroy it with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 556 times.
Similar Threads
Accessing the HashMap object
how to access object inside static block
2 Synchronization blocks with same object
Class not compiling
synchroniztion of map
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 10:24:20.