Middle — Middle+
What methods can be used to create a collection that is safe for use in a multithreaded environment?
sobes.tech AI
Answer from AI
To create thread-safe collections in Java, you can use several approaches:
- Synchronized collections from Collections
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
- Collections from the java.util.concurrent package
ConcurrentHashMap— a thread-safe version of HashMapCopyOnWriteArrayList— a thread-safe list, optimal for frequent reads and infrequent modifications
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
- Using locks (Locks)
You can wrap regular collections in synchronization blocks or use ReentrantLock to control access.
The choice of method depends on performance requirements and the nature of operations (read/write).