Search code examples
javamultithreadingconcurrentmodification

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?


Solution

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