In this post under Java Collections, I will show with example how to create a synchronized collection.
Below is the complete main code for your reference.
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.List;
7
8 public class SyncCollectionDemo {
9 public static void main(String[] args) {
10 List<Integer> integerList = new ArrayList<>(0);
11 integerList.add(1);
12 integerList.add(2);
13 integerList.add(3);
14 integerList.add(4);
15 integerList.add(5);
16
17 Collection<Integer> output = Collections.synchronizedCollection(integerList);
18
19 System.out.println(output);
20 }
21 }
In the above code, I create a list of integers and populate it with elements.
Then at line 17, I call the static “synchronizedCollection” method available on “Collections” class.
This method will take a collection as an argument returns a synchronized collection.
In this way we can create a synchronized collection.
Please note once we obtain a synchronized collection, any modification to the source collection will also affect the synchronized collection and vice versa.
“Collections” class also has “synchronizedList” and “synchronizedSet” static utility methods.