Junior
How can synchronized objects of standard collections in Java be obtained?
sobes.tech AI
Answer from AI
Using static methods of the Collections class:
Collections.synchronizedCollection(Collection<T> c)Collections.synchronizedList(List<T> list)Collections.synchronizedMap(Map<K,V> m)Collections.synchronizedSet(Set<T> s)Collections.synchronizedSortedMap(SortedMap<K,V> m)Collections.synchronizedSortedSet(SortedSet<T> s)
These methods return "wrappers" around the original collections, which delegate method calls to the original collections but do so within a synchronized block, using the wrapper object as the monitor.
Example:
import java.util.*;
// Non-synchronized list
List<String> nonSyncList = new ArrayList<>();
// Get a synchronized version
List<String> syncList = Collections.synchronizedList(nonSyncList);
// Now access to syncList from multiple threads will be safe,
// because the methods of syncList are synchronized.
// Example usage in a thread
new Thread(() -> {
syncList.add("Hello from thread 1");
}).start();
new Thread(() -> {
syncList.add("Hello from thread 2");
}).start();
// To iterate over a synchronized collection from multiple threads,
// you need to explicitly synchronize on the wrapper object.
synchronized (syncList) {
for (String item : syncList) {
System.out.println(item);
}
}
It is important to remember that for iterating over such a synchronized collection in a multithreaded environment, explicit synchronization on the wrapper object is required, as the iterator() and forEach() methods are not atomically synchronized with the iteration.