![]() |
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. Making ArrayList Thread-Safe in JavaTo make ArrayList Thread-Safe, we can follow the below approach: Syntax:// It is a general syntax
public static <T> List<T> synchronizedList(List<T> list)
//Use it for that code
// Create a regular ArrayList
List<T> normalList = new ArrayList<>();
// Make it thread-safe using Collections.synchronizedList
List<T> synchronizedList = Collections.synchronizedList(normalList);
The synchronizedList() method of the Java Collections class is used to get a synchronized (thread-safe) version of a specified list. This method wraps up our original list and returns a synchronized view of it. Program to make ArrayList Thread-Safe in JavaJava
Output
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:
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |