DEV Community

loading...

Synchronized ArrayList in Java

aryan19694946 profile image aryan ・1 min read

Implementation of arrayList is not synchronized is by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally. Structural modification means the addition or deletion of the element from the list or explicitly resizes the backing array. Changing the value of existing element is not structural modification.

See Reference: https://www.java8net.com/2020/03/synchronized-arraylist-in-java.html

import java.util.*;

class ArrayListExample
{
public static void main (String[] args)
{
List list =
Collections.synchronizedList(new ArrayList());

    list.add("A"); 
    list.add("B"); 
    list.add("C"); 

    synchronized(list) 
    { 
        // must be in synchronized block 
        Iterator it = list.iterator(); 

        while (it.hasNext()) 
            System.out.println(it.next()); 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

}

See Reference: https://www.java8net.com/2020/03/synchronized-arraylist-in-java.html

Further Readings
https://www.java8net.com/2020/03/java-arraylist-common-program-examples.html
https://www.java8net.com/2020/02/how-to-sort-arraylist-in-java.html
https://www.java8net.com/2020/03/initialize-arraylist-in-java.html
https://www.java8net.com/2020/03/how-to-remove-duplicates-from-arraylist-in-java.html
https://www.java8net.com/2020/03/arraylist-to-hashmap-in-java.html

Discussion (0)

pic
Editor guide