Junior — Middle
Can you give examples of collection data structures that ensure thread safety?
sobes.tech AI
Answer from AI
In Java, there are several collections that provide thread safety:
Vector— a thread-safe version ofArrayList, with all methods synchronized.Hashtable— a thread-safe version ofHashMap.- Collections from the
java.util.concurrentpackage:ConcurrentHashMap— a high-performance thread-safe hash table.CopyOnWriteArrayList— a thread-safe list, optimal for scenarios with frequent reads and infrequent modifications.BlockingQueueand its implementations (LinkedBlockingQueue,ArrayBlockingQueue) — thread-safe queues with blocking operations.
Example of using ConcurrentHashMap:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
Integer value = map.get("key");
These structures allow safe working with collections from multiple threads without external synchronization.