Java OCA OCP Practice Question 2519

Question

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.}
  • a Because code at lines 2 and 3 uses ConcurrentHashMap, operations in method manipulateMap() are thread safe.
  • b Operations in manipulateMap() will be thread safe if lines 8 and 9 are replaced with map.putIfAbsent(key,value);.
  • c If line 2 is replaced with the following code, there won't be any concurrency issues with manipulateMap(): static final ConcurrentHashMap<Integer,String> map =.
  • d Removing code at lines 4, 5, and 6 will ensure calling manipulateMap() won't override any values.


b

Note

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.




PreviousNext

Related