user1656546
user1656546

Reputation: 93

Exception while removing from list used by thread

thats part of my code:

public List<Integer> _list = new ArrayList<>();

public void removeInteger(Integer i)
{
    _list.remove(i);
}

public class CheckThread implements Runnable
{
    @Override
    public void run()
    {
        synchronized(_list) 
        {
            Iterator<Integer> it=_list.iterator(); 
            while(it.hasNext()) 
            {
                Integer i = it.next();
            }
        }
    }
}

Thread is running all the time(didnt write that part) and when i remove from list using removeInteger method, i have got ConcurrentModificationException. Any idea how to solve that problem?

Upvotes: 0

Views: 257

Answers (4)

Satheesh Cheveri
Satheesh Cheveri

Reputation: 3679

You may try some thing like below ( you condition can be made better according to your requirements)

public void removeInteger(Integer i)
{
    Iterator iter = _list.iterator();
    int count=0;
    while(iter.hasNext()){
         if(count==i){
             _list.remove(i);
             break;
         }
    }
}

Upvotes: 0

Vega
Vega

Reputation: 504

  • If you want to remove while iterating based on a condition write your condition inside the while loop and you can remove the objects using iterator's it.remove() like below

            Iterator<Integer> it=_list.iterator(); 
            while(it.hasNext()) 
            {
                Integer i = it.next();
                if(i<10){
                  it.remove();
                }
            }
    

Upvotes: 0

Uriel Frankel
Uriel Frankel

Reputation: 14622

You should use it.remove() when you need to remove an element.

Upvotes: 2

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

- You must synchronize remove() method, else any otherwise any other thread can access the list and try to remove element from it while other is putting element in it..

 public  synchronized void removeInteger(Integer i)
{
    _list.remove(i);
}

Upvotes: 0

Related Questions