How to Implement a Thread-Safe Resizable Array in Java?
Last Updated :
08 Feb, 2024
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.
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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ThreadSafeResizableArray {
public static void main(String[] args) {
List<Integer> threadSafeArray = Collections.synchronizedList( new ArrayList<>());
threadSafeArray.add( 1 );
threadSafeArray.add( 2 );
threadSafeArray.add( 3 );
synchronized (threadSafeArray) {
for (Integer element : threadSafeArray) {
System.out.println(element);
}
}
}
}
|
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
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreadSafeResizableArray {
public static void main(String[] args) {
List<Integer> threadSafeArray = new CopyOnWriteArrayList<>();
threadSafeArray.add( 1 );
threadSafeArray.add( 2 );
threadSafeArray.add( 3 );
for (Integer element : threadSafeArray) {
System.out.println(element);
}
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...