Friday, 15 August 2014

How to synchronize List

List is non-synchronized in Java. So to perform thread-safe operations,you must synchronize List.

There are two ways.
   1. Synchronizing the list explicitly. 
   2. Use 'Collections.synchronizedList' method.

import java.util.*;

public class ListEx {
    public static void main(String args[]){
        List<Integer> myList = Collections.synchronizedList(new ArrayList<>());
        
        myList.add(10);
        myList.add(20);
        myList.add(30);
        
        System.out.println(myList);
    }
}

Output
[10, 20, 30]



                                                             Home

No comments:

Post a Comment