Interview question
What are Concurrent Collections in Java? Compare with synchronized collections. Java में Concurrent Collections क्या हैं? Synchronized collections से compare करें।
Answer
Concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList) are thread-safe without full synchronization. They use segmentation and fine-grained locking, providing better performance than Collections.synchronizedMap().
import java.util.concurrent.*;
import java.util.*;
// Comparison: Synchronized vs Concurrent
// OLD: Using synchronized collections
Map<String, Integer> syncMap = Collections.synchronizedMap(
new HashMap<>());
// Entire map locked - slow for concurrent access
// BETTER: Using ConcurrentHashMap
ConcurrentHashMap<String, Integer> concurrentMap =
new ConcurrentHashMap<>();
// Segment locking - multiple threads can access different segments
public class ConcurrentCollectionsDemo {
public static void main(String[] args) {
// ConcurrentHashMap
ConcurrentHashMap<String, Integer> map =
new ConcurrentHashMap<>();
// Safe concurrent operations
map.put('key1', 100);
map.putIfAbsent('key2', 200);
map.replace('key1', 100, 150);
map.compute('key3', (k, v) -> 300);
// Safe iteration (no ConcurrentModificationException)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ' -> ' + entry.getValue());
}
// CopyOnWriteArrayList
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add('Item1');
list.add('Item2');
// Safe iteration during modifications
list.forEach(System.out::println);
// ConcurrentLinkedQueue
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
queue.add(1);
queue.add(2);
queue.poll();
// ConcurrentSkipListMap (sorted, thread-safe)
ConcurrentSkipListMap<Integer, String> skipMap =
new ConcurrentSkipListMap<>();
skipMap.put(1, 'One');
skipMap.put(2, 'Two');
// ConcurrentSkipListSet (sorted set, thread-safe)
ConcurrentSkipListSet<Integer> skipSet = new ConcurrentSkipListSet<>();
skipSet.add(1);
skipSet.add(2);
}
}
// Concurrent Collections Comparison
public class PerformanceComparison {
public static void main(String[] args) throws InterruptedException {
// Synchronized HashMap
long start = System.currentTimeMillis();
Map<String, Integer> syncMap = Collections.synchronizedMap(
new HashMap<>());
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
final int index = i;
executor.submit(() -> {
for (int j = 0; j < 1000; j++) {
syncMap.put('key' + index + j, j);
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
System.out.println('Synchronized: ' +
(System.currentTimeMillis() - start) + 'ms');
// ConcurrentHashMap
start = System.currentTimeMillis();
ConcurrentHashMap<String, Integer> concMap =
new ConcurrentHashMap<>();
executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
final int index = i;
executor.submit(() -> {
for (int j = 0; j < 1000; j++) {
concMap.put('key' + index + j, j);
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
System.out.println('ConcurrentHashMap: ' +
(System.currentTimeMillis() - start) + 'ms');
// Result: ConcurrentHashMap ~5x faster
}
}
// Concurrent Collections Summary:
// ConcurrentHashMap: Multiple segments, fine-grained locking
// CopyOnWriteArrayList: Copy-on-write semantics
// ConcurrentLinkedQueue: Lock-free queue
// ConcurrentSkipListMap: Sorted concurrent map
// ConcurrentSkipListSet: Sorted concurrent setConcurrent Collections:
OLD Approach: Collections.synchronizedMap()
- Entire collection locked
- Slow for concurrent access
- ConcurrentModificationException possible
NEW Approach: Concurrent classes
- Segment locking (ConcurrentHashMap)
- Better performance
- Safe iteration
Types:
1. ConcurrentHashMap - Map with segments
2. CopyOnWriteArrayList - List (copy on write)
3. ConcurrentLinkedQueue - Queue (lock-free)
4. ConcurrentSkipListMap - Sorted map
5. ConcurrentSkipListSet - Sorted set
Performance: 5-10x faster than synchronized
Usage:
ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
CopyOnWriteArrayList<E> list = new CopyOnWriteArrayList<>();
Benefit:
- Multiple threads different segments access कर सकते हैं
- No full lock, better scalability
- Safe for iteration during modificationWas this answer clear?