1. What is ConcurrentHashMap in Java?
Answer:
Explanation:
ConcurrentHashMap is a thread-safe variant of HashMap in Java, designed for concurrent access.
2. How does ConcurrentHashMap achieve thread-safety?
Answer:
Explanation:
ConcurrentHashMap achieves thread-safety by dividing the map into segments and only locking the necessary segment during updates.
3. Can ConcurrentHashMap contain null values or null keys?
Answer:
Explanation:
ConcurrentHashMap does not allow null values or null keys.
4. What is the default concurrency level of a ConcurrentHashMap?
Answer:
Explanation:
The default concurrency level of ConcurrentHashMap is 16, which means it internally manages 16 segments.
5. Which method is used to replace a value in ConcurrentHashMap?
Answer:
Explanation:
The replace() method is used for replacing a value associated with a given key in ConcurrentHashMap.
6. What happens if two threads update a ConcurrentHashMap simultaneously?
Answer:
Explanation:
ConcurrentHashMap is designed to handle concurrent updates without corrupting the map.
7. Can you use an iterator to traverse a ConcurrentHashMap?
Answer:
Explanation:
An iterator can be used to traverse a ConcurrentHashMap, and it provides a weakly consistent view of the map.
8. How does ConcurrentHashMap differ from Hashtable?
Answer:
Explanation:
ConcurrentHashMap offers better scalability compared to Hashtable due to its segment-level locking.
9. Is the iteration over ConcurrentHashMap fail-safe?
Answer:
Explanation:
Iterators of ConcurrentHashMap are fail-safe and reflect the state of the map as of the time the iterator was created.
10. How do you check if a ConcurrentHashMap is empty?
Answer:
Explanation:
The isEmpty() method checks if the ConcurrentHashMap has no key-value mappings.