![]() |
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 JavaWe 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 JavaUsing Collections.synchronizedList, let’s examine an example: Java
Output
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
Output
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. |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |