How to Synchronize ArrayList in Java

sometimes we want to make a list synchronized but by default list in java is not synchronized.

1.so we can use synchronizedList() method available in Collections class.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SynchronizeListExample {

    
public static void main(String[] args) {
        
List list=Collections.synchronizedList(new ArrayList());
        
      list.add("a");
      list.add("b");
      list.add("c");
    
        synchronized (list) {
        
         Iterator it=list.iterator();
         while(it.hasNext()){    
         System.out.println(it.next());        
            }
        }
        
        
        
        
        
    }
    
}

2.Using CopyOnWriteArrayList

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListExample {

	
	public static void main(String[] args) {
		
		
		
	CopyOnWriteArrayList list=new CopyOnWriteArrayList();
	list.add("a");
	list.add("b");
	list.add("c");
		
		
	//Synchronized block is not required in this method
	Iterator iterator = list.iterator(); 
	while (iterator.hasNext())
	    System.out.println(iterator.next());
	  }
	
}


Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s