Search code examples
javaiteratorpriority-queueconcurrentmodification

Java concurrentmodificationexception in priority queue


I have a problem iterating my priority queue which cost Concurrentmodificationexception.

code for iterating:

Queue<Patient> pq = new PriorityQueue<Patient>();
 Iterator<Patient> it = pq.iterator();    
            while(iter.hasNext()){
                Patient current = iter.next();
                if(current.getName().equals(patientName)){

                    pq.remove(p);
                    }


                } 

There error says that iter.next() cost Concurrentmodificationexception. May i please know how to resolve this? i have search the internet but the still cant find a solution to this.


Solution

  • Change your code to following for solving it -

    Queue<Patient> pq = new PriorityQueue<Patient>();
     Iterator<Patient> iter = pq.iterator();    
                while(iter.hasNext()){
                    Patient current = iter.next();
                    if(current.getName().equals(patientName)){
    
                        iter.remove();
                        }
    
    
                    } 
    

    Explanation ConcurrentModificationException is thrown from next() method of iterator, if there is any structural change in the underlying collection (in your case Queue) i.e. any element is added or removed in the queue directly. It is called Fail Fast Iterator.