Page 1 of 1
About Question enthuware.ocpjp.v7.2.1510 :
Posted: Mon Feb 01, 2016 2:56 pm
by krohani
Hi Paul - So just to clarify. Just because we use a ConcurrentHashMap object does not guarantee thread-safety for all operations. ConcurrentHashMap simply provides us with a few extra methods which are thread safe however we if use any of the methods inherited from Map or Abstract map then those methods (even if used on a ConcurrentHashMap) are just regular non thread safe methods.
So if my understanding is correct then the benefit of using a ConcurrentHashMap here is simply getting the additional methods which allow thread safe writes and read?
Is putIfAbsent the only additional method provided that is thread safe or are there others?
Re: About Question enthuware.ocpjp.v7.2.1510 :
Posted: Mon Feb 01, 2016 9:48 pm
by admin
No, all its methods are thread safe (see this
https://docs.oracle.com/javase/7/docs/a ... shMap.html ). But if you use multiple methods without locking, even though its internal data structure will be safe, but from an application perspective, it will work as thread unsafe. That is what this question illustrates. Another thread can insert the same key-value after one thread calls containsKey and before calling put. You need to either put both the calls within a synchronized block or use putIfAbsent.
For details please go through the link given above.
Re: About Question enthuware.ocpjp.v7.2.1510 :
Posted: Tue Feb 02, 2016 2:26 pm
by krohani
Got it, thanks!
Re: About Question enthuware.ocpjp.v7.2.1510 :
Posted: Wed Oct 05, 2022 3:55 am
by sohamdatey22
is this correct understanding, that putIfAbsent() is a thread safe method, just because it is concurrent hashmap?
o'wise, the nearest possible solution will be the synchronized block.
thanks.
Re: About Question enthuware.ocpjp.v7.2.1510 :
Posted: Wed Oct 05, 2022 4:05 am
by admin
Not sure I understand you correctly. putIfAbsent of ConcurrentMap is thread-safe. Meaning, you may call this method multiple times from different threads simultaneously without getting the map data corrupted.