Sobes.tech
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:

  1. 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.
  2. Collections from the java.util.concurrent package:

    • 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 of Map, 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 to CopyOnWriteArrayList, but for sets.
      • ConcurrentLinkedQueue: Thread-safe, lock-free implementation of Queue.
      • ConcurrentLinkedDeque: Thread-safe, lock-free implementation of Deque.
      • ConcurrentSkipListMap: Thread-safe, scalable implementation of SortedMap.
      • ConcurrentSkipListSet: Thread-safe, scalable implementation of SortedSet.
      • 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.