Search code examples
javaglobal-variableslocal-variablesconcurrentmodification

ConcurrentModificationException with global variables but not local with local variables


In the following function I have declared local variables allPeopel and itr(they are overriding global variables). If I comment out the local variables (between the Astrixes below), then a ConcurrentModificationError is thrown. However, if I use local variables instead of global variables then the code works fine. I don't understand why this is the case? There are many other functions in the class so I'm trying to use global variables for more efficient code.

   public void removeAPerson(){
        int id;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter ID of person to delete > ");
        id = sc.nextInt();
        sc.nextLine();
        System.out.println();

        /*************************************/
        ArrayList<Person> allPeople;
        allPeople = Person.getAllPeople();
        Iterator itr = allPeople.iterator();
        /*************************************/

        while(itr.hasNext()){
            Person obj = (Person) itr.next();
            int ID = obj.getID2();
            if(ID == id){
                itr.remove();
                break;
            }
        }
    }

Solution

  • Using local variables, each time a thread calls your method creates a new instance of these variables, that are not available to any other thread (unless you specifically allow for passing the references). So, no other thread can modify your objects.

    Using global (I think you mean instance variables, attributes), all of the threads that have access to your object has access to those attributes of the object (let it be directly, let it be by running your object methods) and can modify them while your other thread is running the iteration. Since the iterator can detect when the Collection that is being iterated has been modified, when this happens it throws the exception (which means nothing else that "I was iterating all of the objects of the collection but these objects are no longer the same so this is too confusing and I fail".