Examine the following code and select the correct options.
1. class UseConcurrentHashMap { 2. static final ConcurrentMap<Integer, String> map = 3. new ConcurrentHashMap<>(); 4. static {//w w w . java2s . co m 5. //code to populate map 6. } 7. static void manipulateMap(Integer key, String value) { 8. if(!map.containsKey(key)) 9. map.put(key, value); 10. } 11.}
manipulateMap()
are thread safe.manipulateMap()
will be thread safe if lines 8 and 9 are replaced with map.putIfAbsent(key,value);
.manipulateMap()
: static final ConcurrentHashMap<Integer,String> map =.manipulateMap()
won't override any values.b
Option (a) is incorrect.
The individual operations of classes ConcurrentHashMap, containsKey()
, and put are atomic and safe to be used concurrently by multiple threads.
But when these methods are used together in manipulateMap
, it doesn't guarantee thread safety for the time between these two method calls.
Multiple calls to atomic operations don't form an atomic operation.
You need external locking or synchronization to make such operations thread safe.
Option (b) is correct because method putIfAbsent()
in ConcurrentHashMap combines two steps: checking for the existence of a key and replacing its value in a method, and synchronizing the key-value pair access across threads.
Options (c) and (d) are incorrect because these steps will not make a difference in this case.