Program to make ArrayList Thread-Safe in Java
Java
// Java Program to make ArrayList Thread-Safe in Java import java.util.ArrayList; import java.util.Collections; import java.util.List; class GFG { public static void main(String[] args) { // Create a regular ArrayList List<String> normalList = new ArrayList<>(); // Make it thread-safe using Collections.synchronizedList List<String> synchronizedList = Collections.synchronizedList(normalList); // Now synchronizedList can be used safely in a multi-threaded environment // Operations on this list are automatically synchronized // Adding elements to the synchronized list synchronizedList.add( "Element 1" ); synchronizedList.add( "Element 2" ); // Iterating over the synchronized list System.out.println( "Iterating over the synchronized list:" ); for (String element : synchronizedList) { System.out.println( "Element: " + element); } // Modifying the synchronized list synchronizedList.remove( "Element 1" ); System.out.println( "After removing 'Element 1'..." ); // Iterating over the synchronized list again System.out.println( "Iterating over the synchronized list after removal:" ); for (String element : synchronizedList) { System.out.println( "Element: " + element); } } } |
Iterating over the synchronized list: Element: Element 1 Element: Element 2 After removing 'Element 1'... Iterating over the synchronized list after removal: Element: Element 2
Explanation of the Program:
- In the above program, first we have created a regular ArrayList.
- After that we make it thread-safe using Collections.synchronizedList().
- Now synchronizedList can be used safely in a multi-threaded environment.
- And now operations on the list are automatically get synchronized.
- Now we have added elements to the synchronized list.
- Then, iterating over the synchronized list and modified.
- In final, we have done iteration over the synchronized list again.
To know more about the topic refer to this article Synchronization of ArrayList in Java.
How to make ArrayList Thread-Safe in Java?
In Java, Thread is the smallest unit of execution within the program. It represents an independent path of execution that can run concurrently with other threads. When dealing with multi-threaded applications, where multiple threads are accessing and modifying data concurrently, it’s crucial to ensure that data structures like ArrayList are handled in a way that prevents conflicts and maintains data integrity.
In this article, we will explore the basic process of making an ArrayList thread-safe in a Java program.