Senior
Name 2-3 examples of thread-safe collections.
sobes.tech AI
Answer from AI
In Java, thread-safe collections ensure correct operation when accessed concurrently from multiple threads without external synchronization. Examples:
- ConcurrentHashMap — a thread-safe version of HashMap that allows efficient concurrent reading and writing.
- CopyOnWriteArrayList — a thread-safe list that creates a copy of the internal array upon modifications, suitable for scenarios with frequent reads and infrequent writes.
- BlockingQueue (e.g., LinkedBlockingQueue) — a queue with blocking operations used for thread-safe data exchange between threads.
Example of using ConcurrentHashMap:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
int value = map.get("key");