Short Summary:
Java Collection Framework provides dynamic data structures. It includes List, Set, Queue, Deque, and Map along with concurrent and fail-safe mechanisms.
1️⃣ Collection Framework Hierarchy
Iterable
|
Collection
/ | \
List Set Queue
\
Deque
Map (Separate Hierarchy)
2️⃣ Fail-Fast vs Fail-Safe
Short Answer:
Fail-Fast throws ConcurrentModificationException. Fail-Safe does not throw exception and works on copy.
Fail-Fast
- Works on original collection.
- Detects structural modification.
- Throws ConcurrentModificationException.
- Examples: ArrayList, HashMap
Listlist = new ArrayList<>(); list.add("Java"); for(String s : list) { list.add("Spring"); // Exception }
Fail-Safe
- Works on clone/copy.
- No exception thrown.
- Safe in multi-threading.
- Examples: ConcurrentHashMap, CopyOnWriteArrayList
3️⃣ Concurrent Collections Deep Dive
Short: Thread-safe collections designed for high concurrency.
| Collection | Feature |
| ConcurrentHashMap | Bucket-level locking (Java 8 uses CAS) |
| CopyOnWriteArrayList | Creates new copy on modification |
| BlockingQueue | Used in producer-consumer |
| ConcurrentLinkedQueue | Non-blocking queue |
ConcurrentHashMap Internal Working
- Java 7 → Segmented locking
- Java 8 → CAS + synchronized on bucket
- No null key/value allowed
- Better performance than Hashtable
4️⃣ Map Hierarchy Explained
Map
/ \
HashMap SortedMap
| |
LinkedHashMap TreeMap
|
ConcurrentHashMap
Map Implementations Comparison
| Feature | HashMap | LinkedHashMap | TreeMap | ConcurrentHashMap |
| Order | No | Insertion order | Sorted | No |
| Thread Safe | No | No | No | Yes |
| Null Key | 1 allowed | Allowed | Not allowed | Not allowed |
| Time Complexity | O(1) | O(1) | O(log n) | O(1) |
5️⃣ Important Interview Concepts
- Fail-fast uses modCount mechanism.
- Fail-safe works on snapshot.
- Map is not part of Collection hierarchy.
- ConcurrentHashMap avoids full locking.
- Hashtable is legacy class.
- CopyOnWriteArrayList best for read-heavy scenarios.
0 comments