How to synchronize List, Set and Map elements?

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(&quot;Apple&quot;);
synchronizedList.add(&quot;Banana&quot;);

// 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(&quot;Apple&quot;);
synchronizedSet.add(&quot;Banana&quot;);

// 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(&quot;Apple&quot;, 1);
synchronizedMap.put(&quot;Banana&quot;, 2);

// Iterate over the synchronized map
synchronized (synchronizedMap) {
    for (Map.Entry&lt;String, Integer&gt; entry : synchronizedMap.entrySet()) {
        System.out.println(entry.getKey() + &quot;: &quot; + 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.