Middle
What thread-safe collections do you know in Java?
sobes.tech AI
Answer from AI
In the Java Collections Framework, there are thread-safe collections implemented in two main ways:
-
Synchronized Wrappers:
- Wrap standard, non-thread-safe collections (e.g.,
ArrayList,HashMap,HashSet). - All collection methods are synchronized.
- Example of obtaining synchronized collections:
// Getting a synchronized list List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>()); // Getting a synchronized set Set<String> synchronizedSet = Collections.synchronizedSet(new HashSet<>()); // Getting a synchronized map Map<String, String> synchronizedMap = Collections.synchronizedMap(new HashMap<>()); - Disadvantage: Low performance under high concurrency, as locking occurs on the entire collection.
- Wrap standard, non-thread-safe collections (e.g.,
-
Collections from the
java.util.concurrentpackage:- Designed specifically for multi-threaded environments.
- Achieve thread safety through various mechanisms (e.g., fine-grained locking, CAS operations).
- Provide better performance for concurrent operations compared to synchronized wrappers.
- Main examples:
ConcurrentHashMap: Thread-safe implementation ofMap, providing high throughput for read and write operations.CopyOnWriteArrayList: List that creates a new copy of the underlying array upon modification. Suitable for collections with frequent read and infrequent write operations.CopyOnWriteArraySet: Similar toCopyOnWriteArrayList, but for sets.ConcurrentLinkedQueue: Thread-safe, lock-free implementation ofQueue.ConcurrentLinkedDeque: Thread-safe, lock-free implementation ofDeque.ConcurrentSkipListMap: Thread-safe, scalable implementation ofSortedMap.ConcurrentSkipListSet: Thread-safe, scalable implementation ofSortedSet.- Blocking queues (
BlockingQueue,BlockingDeque) - e.g.,ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue,DelayQueue,SynchronousQueue,LinkedTransferQueue. Used for coordinating producer and consumer threads.
The choice between synchronized wrappers and collections from java.util.concurrent depends on specific performance requirements and the nature of usage in a multi-threaded environment (frequency of read/write operations, level of parallelism). In most modern multi-threaded applications, it is preferable to use collections from java.util.concurrent.