In Java, you can create a synchronized List using the Collections.synchronizedList() method. This method returns a synchronized (thread-safe) view of the specified list. All access to the returned list is synchronized on a common lock.
Here’s an example code that demonstrates how to create a synchronized List:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");
List<String> synchronizedList = Collections.synchronizedList(list);
// Access the synchronized list in a synchronized block
synchronized (synchronizedList) {
System.out.println("Iterating through synchronized list:");
for (String element : synchronizedList) {
System.out.println(element);
}
}
}
}
In this example, we create an ArrayList and add three strings to it. We then create a synchronized view of the ArrayList using the Collections.synchronizedList() method. Finally, we access the synchronized list in a synchronized block and iterate through its elements.
Note that while the synchronized list is thread-safe for individual method calls, it’s not sufficient to synchronize on the list itself if you need to perform compound operations (like iteration or conditionally accessing and modifying the list), as that would not guarantee the required atomicity of the operations. Instead, you would need to manually synchronize on a common lock for those operations, or consider using more advanced concurrency mechanisms like the java.util.concurrent package.