About Question enthuware.ocpjp.v7.2.1510 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
krohani
Posts: 31
Joined: Tue Oct 06, 2015 1:57 pm
Contact:

About Question enthuware.ocpjp.v7.2.1510 :

Post 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?

admin
Site Admin
Posts: 10062
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1510 :

Post 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.
If you like our products and services, please help us by posting your review here.

krohani
Posts: 31
Joined: Tue Oct 06, 2015 1:57 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1510 :

Post by krohani »

Got it, thanks!

sohamdatey22
Posts: 28
Joined: Sun Sep 11, 2022 3:55 am
Contact:

Re: About Question enthuware.ocpjp.v7.2.1510 :

Post 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.

admin
Site Admin
Posts: 10062
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1510 :

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 83 guests