In Java, collections like List
, Set
, and Map
are not thread-safe by default. To make them thread-safe, you can use various synchronization mechanisms provided by the Java Collections Framework. Here’s how you can synchronize these collections:
1. Synchronizing a List
To synchronize a List
, you can use Collections.synchronizedList()
method. This method returns a synchronized (thread-safe) view of the specified list.
Example:
import java.util.*; public class SynchronizedListExample {
public static void main(String args) {
List<String> list = new ArrayList<>();
List<String> synchronizedList = Collections.synchronizedList(list);
synchronizedList.add("Apple");
synchronizedList.add("Banana");
// Iterate over the synchronized list
synchronized (synchronizedList) {
for (String fruit : synchronizedList) {
System.out.println(fruit);
}
}
}
}
2. Synchronizing a Set
To synchronize a Set
, use Collections.synchronizedSet()
method. This method returns a synchronized (thread-safe) view of the specified set.
Example:
import java.util.*; public class SynchronizedSetExample {
public static void main(String args) {
Set<String> set = new HashSet<>();
Set<String> synchronizedSet = Collections.synchronizedSet(set);
synchronizedSet.add("Apple");
synchronizedSet.add("Banana");
// Iterate over the synchronized set
synchronized (synchronizedSet) {
for (String fruit : synchronizedSet) {
System.out.println(fruit);
}
}
}
}
3. Synchronizing a Map
To synchronize a Map
, use Collections.synchronizedMap()
method. This method returns a synchronized (thread-safe) view of the specified map.
Example:
import java.util.*; public class SynchronizedMapExample {
public static void main(String args) {
Map<String, Integer> map = new HashMap<>();
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(map);
synchronizedMap.put("Apple", 1);
synchronizedMap.put("Banana", 2);
// Iterate over the synchronized map
synchronized (synchronizedMap) {
for (Map.Entry<String, Integer> entry : synchronizedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
}
Summary
- List: Use
Collections.synchronizedList()
to get a synchronized view of a list. - Set: Use
Collections.synchronizedSet()
to get a synchronized view of a set. - Map: Use
Collections.synchronizedMap()
to get a synchronized view of a map.