Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create Synchronized arraylist

i have created synchronized arrayList like this

import java.text.SimpleDateFormat;
import java.util.*;


class HelloThread  
{

 int i=1;
 List arrayList;
  public  void go()
  {
 arrayList=Collections.synchronizedList(new ArrayList());
 Thread thread1=new Thread(new Runnable() {

  public void run() {
  while(i<=10)
  {
   arrayList.add(i);
   i++;
  }
  }
 });
 thread1.start();
 Thread thred2=new Thread(new Runnable() {
  public void run() {
     while(true)
     {
   Iterator it=arrayList.iterator();
      while(it.hasNext())
      {
       System.out.println(it.next());
      }
     }
  }
 });
 thred2.start();
  }
 }

public class test
{
  public static void main(String[] args)
  {
   HelloThread hello=new HelloThread();
   hello.go();
  }
}

but getting exception like this

Exception in thread "Thread-1" java.util.ConcurrentModificationException

anything wrong in my approach ?

like image 580
Lalchand Avatar asked Sep 28 '10 15:09

Lalchand


People also ask

How do you create a synchronized ArrayList?

There are two ways to create a Synchronized ArrayList.Collections. synchronizedList() method. 2. Using CopyOnWriteArrayList.

What is synchronization ArrayList?

Being synchronized means that every operation is thread safe - if you use the same vector from two threads at the same time, they can't corrupt the state. However, this makes it slower. If you are working in a single threaded environment (or the list is limited to a thread and never shared), use ArrayList.

How do I create a synchronized collection?

Here are the detailed Steps: Create an ArrayList. Populate the arrayList with elements, with add(E e) API method of ArrayList. Invoke the synchronizedList(List list) API method of Collections to get the synchronized list from the provided ArrayList.

Are ArrayList methods synchronized?

We can use Collections. synchronizedList(List<T>) method to synchronize collections in java. The synchronizedList(List<T>) method is used to return a synchronized (thread-safe) list backed by the specified list.


1 Answers

Iterator of synchronizedList is not (and can't be) synchronized, you need to synchronize on the list manually while iterating (see javadoc):

synchronized(arrayList) {
    Iterator it=arrayList.iterator(); 
    while(it.hasNext()) { 
        System.out.println(it.next()); 
   } 
}

Another approach is to use a CopyOnWriteArrayList instead of Collections.synchronizedList(). It implements a copy-on-write semantic and therefore doesn't require synchronization.

like image 183
axtavt Avatar answered Oct 13 '22 04:10

axtavt