Thread-Safe Resizable Array in Java
We may use concurrent collections like CopyOnWriteArrayList or Collections.synchronizedList to create a thread-safe resizable array. Data corruption is avoided via synchronization, which guarantees that only one thread may access the array at a time.
Program to Implement Thread Safe Resizable Array in Java
Using Collections.synchronizedList, let’s examine an example:
Java
// Java Program to Implement Thread Safe Resizable Array import java.util.ArrayList; import java.util.Collections; import java.util.List; // Driver Class public class ThreadSafeResizableArray { // Main Function public static void main(String[] args) { // Creating a thread-safe resizable array List<Integer> threadSafeArray = Collections.synchronizedList( new ArrayList<>()); // Adding elements in a thread-safe manner threadSafeArray.add( 1 ); threadSafeArray.add( 2 ); threadSafeArray.add( 3 ); // Iterating over the array using a synchronized block synchronized (threadSafeArray) { for (Integer element : threadSafeArray) { System.out.println(element); } } } } |
1 2 3
Explaination of the above Program:
In this example, we use Collections.synchronizedList to generate a thread-safe resizable array. An existing list is wrapped by the synchronizedList method, which then produces a synchronized (thread-safe) list.
As an alternative, CopyOnWriteArrayList may be utilized:
Java
// Java Program to Implement Thread Safe Resizable Array import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ThreadSafeResizableArray { public static void main(String[] args) { // Creating a thread-safe resizable array List<Integer> threadSafeArray = new CopyOnWriteArrayList<>(); // Adding elements threadSafeArray.add( 1 ); threadSafeArray.add( 2 ); threadSafeArray.add( 3 ); // Iterating over the array for (Integer element : threadSafeArray) { System.out.println(element); } } } |
1 2 3
Explaination of the above Program:
Concurrent collections like CopyOnWriteArrayList provide thread safety without requiring explicit synchronization. To ensure safe iteration, it makes a fresh duplicate of the underlying array each time an element is added or changed.
How to Implement a Thread-Safe Resizable Array in Java?
Multiple threads may securely execute operations like insertion and deletion without risking data corruption when utilizing a thread-safe resizable array. The ArrayList class is a popular Java class, yet it is not thread-safe by default. We may use concurrent collections or synchronization to make it thread-safe.