Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can iterate over and modify this Arraylist?

I have an arrayList which I am sharing between two threads and I am trying to iterate over and modify the list at the same time. I don't want to use the iterator's method, and I have also used the synchronized list but it still gives concurrentmodificationexception.

code is as follows :

public class testing {
  public static void main(String args[]){

  ArrayList<String> al = new ArrayList<String>();
  List<String> sal=Collections.synchronizedList(al);
   String names[] = {"amol","Robin","vikas","shanu","mahesh"};
  for(String x :names){
       al.add(x);
  }      

  Thread t1 = new Thread(new SyncArrayList(sal));
  Thread t2 = new Thread(new SyncArrayList(sal));    
  t1.setName("T1");
  t2.setName("T2");
  t1.start();
  t2.start();

  }   
}

class SyncArrayList implements Runnable
{
 List<String> unsync ;

SyncArrayList(List<String> l){
   this.unsync = l;
}

@Override
public void run() {
    displayUnsyncList();
    addNames();
  }

void displayUnsyncList(){
   synchronized(this){ 
   ListIterator<String> itr = unsync.listIterator();
  while(itr.hasNext()){
      String x = itr.next();
      System.out.println("Thread " +Thread.currentThread().getName() + " is displaying name : "+x);
   } 
  }
 }

void addNames(){
    unsync.add("preet");
   } 

}   
like image 369
Amol Avatar asked Dec 14 '25 02:12

Amol


1 Answers

In multithreaded environment you should consider using CopyOnWriteArrayList which doesn't produce ConcurrentModificationException

like image 65
Cootri Avatar answered Dec 15 '25 15:12

Cootri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!